Variable Length Arrays and Constant Expressions
The C code fragment presented below has the potential to compile successfully with certain compilers:
int main() { int size = 10; int arr[size]; }
According to the C Standard (8.3.4/1), this code is expected to be rejected since the size of the array (arr) needs to be a constant expression. However, it raises questions about the behavior of compilers like gcc 4.8 and Clang 3.2.
Variable Length Arrays (VLAs) come into play in this scenario. VLAs are a C99 feature that gcc and clang have implemented as an extension within C . However, Visual Studio adheres strictly to the standard in this case. The message it generates:
error C2466: cannot allocate an array of constant size 0
indicates that it rightfully interprets the size as zero, which is not permitted in this context.
If you enable the -pedantic flag in both gcc and clang, you will receive warnings regarding the use of VLAs. For instance, gcc states:
warning: ISO C++ forbids variable length array 'arr' [-Wvla] int arr[size]; ^
Moreover, using the -pedantic-errors flag will render this usage an error. Refer to the provided documentation for further information on supported language standards.
The draft C standard defines an integral constant expression in 5.19 (Constant expressions) as follows:
"An integral constant expression is an expression of integral or unscoped enumeration type, implicitly converted to a prvalue, where the converted expression is a core constant expression."
To achieve compliance with the standard, you can initialize size with a literal using const (or constexpr). This would make size an integral constant expression:
const int size = 10; // or constexpr int size = 10;
The corresponding section in the C99 draft standard (6.7.5.2) clarifies that if the size is not present, an incomplete array type is declared. If the size is *, a variable length array type is created without a defined length and can only be used in certain contexts. Otherwise, it's either a regular array type or a variable length array type based on the expression's properties.
The above is the detailed content of Why Do Some Compilers Allow Variable Length Arrays in C While Others Don't?. For more information, please follow other related articles on the PHP Chinese website!