Home > Backend Development > C++ > Do Variable-Length Arrays in C Conform to the Standard?

Do Variable-Length Arrays in C Conform to the Standard?

Susan Sarandon
Release: 2024-12-12 20:53:12
Original
390 people have browsed it

Do Variable-Length Arrays in C   Conform to the Standard?

Variable Length Arrays in C : Exploring Constancy and Standard Compliance

The C code snippet below has raised questions about whether it adheres to the language standard, particularly regarding constant expressions:

int main()
{
  int size = 10;
  int arr[size];
}
Copy after login

In the C Standard (8.3.4/1), the size of an array must be an "integral constant expression." Size, in the example above, appears to lack this property.

Variable Length Arrays (VLA) and Compilation Status

The code compiles successfully with gcc 4.8 and Clang 3.2 because both compilers support variable length arrays (VLAs) as an extension in C . However, Visual Studio CTP rejects the code with an error message suggesting that size is zero. This behavior is consistent with the C Standard, which does not allow arrays of variable size.

Compiler Warnings and Language Extensions

Some compilers, such as gcc and clang, provide warnings when using VLAs with the -pedantic flag. This flag warns about potential non-standard features, indicating that the code violates the C Standard. In this case, the lack of constant size for the array makes VLA usage inappropriate.

Integral Constant Expressions

Integral constant expressions, according to the C draft standard (5.19.3), must satisfy specific conditions. In this instance, size being initialized with a literal qualifies it as an integral constant expression. However, to comply with the C Standard, "const" or "constexpr" should be used to explicitly declare it as such:

const int size = 10;
Copy after login

or

constexpr int size = 10;
Copy after login

Conclusion

While variable length arrays provide flexibility, their use must be balanced against standard compliance. Compilers like Visual Studio adhere to the C Standard and reject code that violates its rules. By understanding the concept of integral constant expressions and considering language extensions, developers can ensure that their code meets both functionality and standardization requirements.

The above is the detailed content of Do Variable-Length Arrays in C Conform to the Standard?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template