Is "int size = 10;" a Constant Expression?
The code snippet:
int main() { int size = 10; int arr[size]; }
raises questions about whether the variable length array (VLA) is a valid C feature.
The Standard's Perspective
The C Standard (8.3.4/1) mandates that array sizes be integral constant expressions, which "size" appears not to be. Compilers like GCC and Clang accept this code due to their support for VLAs as an extension in C . Visual Studio, adhering to the standard, rejects it.
Variable Length Arrays
VLAs are a C99 feature that allows arrays with dynamically determined sizes. GCC and Clang extend this functionality to C . However, VLAs are not part of the C standard and using the -pedantic flag in GCC/Clang will generate warnings or errors.
Integral Constant Expressions
According to the C draft standard (5.19/3), an integral constant expression is an expression of an integral or unscoped enumeration type, implicitly converted to a prvalue, that satisfies the criteria for a core constant expression.
Making "size" a Constant Expression
To adhere to the standard, "size" must be declared an integral constant expression. This can be achieved by:
Conclusion
GCC and Clang's acceptance of VLAs is an extension and not a standard feature in C . Visual Studio's rejection is in compliance with the standard. To use VLA-like functionality in standard C , it's recommended to use const or constexpr to make array sizes integral constant expressions.
The above is the detailed content of Is `int size = 10;` a Valid Constant Expression for Array Sizing in C ?. For more information, please follow other related articles on the PHP Chinese website!