Why does my C++ compiler accept Variable Length Arrays (VLAs) if the feature is not standard?
c++, dynamic-arrays, variable-length-array
Solution
Why does the compiler accept that declaration?
Because its authors chose to make it do so.
GCC in particular allows, by default, a lot of non-standard stuff that was historically accepted by old C compilers. They like "compatibility" in that sense.
What does the standard say about this?
The C++ grammar contains the following rule for array declarations in [dcl.array]:
In a declaration `T D` where `D` has the form `D1` `[` constant-expressionopt `]` attribute-specifier-seqopt
[...] the type of the declarator-id in `D` is "derived-declarator-type-list array of `N` `T`"
In simple terms, this means that only a constant expression can be used to specify the size of an array. In your example, `n` is not a constant expression.
C++ does not have VLAs.
Where you see one being accepted, it is a compiler extension; to find out how that compiler implements such an extension, you would have to ask the compiler's authors (or examine its source, if applicable).
Problem
As we already know, VLA (standardized in C99) are not part of the standard in C++, so the code below is "illegal" in C++: ``` void foo(int n) { int vla[n]; for (int i = 0; i < n; ++i) { vla[i] = i; } } ``` Despite of that the compiler (g++ and clang++) accepts the code as valid syntax, producing just a warning in case `-pedantic` flag is enabled. ISO C++ forbids variable length array ‘vla’ [-Wvla] My questions are: Why does the compiler accept that declaration? Can't the compiler just reject an array in which length `[is-no-know-at-compile-time]`? Is there a sort of compatibility syntax rule to follow? What does the standard say about this? From the assembly code produced, I see the compiler writes in the stack in the loop, like a normal array, but I cannot find anything about the standard behaviour.