Does "int size = 10;" Yield a Constant Expression?
The code snippet below compiles successfully in gcc 4.8 and Clang 3.2:
int main() { int size = 10; int arr[size]; }
According to the C Standard (8.3.4/1), the size of an array must be an integral constant expression. However, it appears that "size" in the code is not an integral constant expression. Is this a compiler bug or an oversight in our understanding?
Visual Studio C rejects this code with the message: "error C2466: cannot allocate an array of constant size 0". This implies that the compiler considers "size" to be zero.
Explanation
gcc and Clang support variable length arrays (VLA) as an extension in C . VLA is a C99 feature that allows the size of an array to be determined at runtime. In the code snippet, "size" is determined at compile-time, but it is not a literal constant. Therefore, "size" is considered a VLA in gcc and Clang.
Visual Studio, on the other hand, does not support VLA and adheres to the C Standard. As a result, it rejects the code because "size" is not a literal constant.
Standard Compliance
The C Standard defines an integral constant expression as an expression that, when evaluated, results in a prvalue of integral or unscoped enumeration type. In this case, "size" is initialized with a literal value (10), which makes it an integral constant expression.
Using the "-pedantic" flag in gcc and Clang will generate a warning about variable length arrays in the code snippet. Using "-pedantic-errors" will make the warning an error.
Solution
To comply with the C Standard, "size" can be declared as a const or constexpr integer:
const int size = 10;
or
constexpr int size = 10;
The above is the detailed content of Is `int size = 10;` a Constant Expression in C : A Compiler Compatibility Issue?. For more information, please follow other related articles on the PHP Chinese website!