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 enable.
ISO C++ forbids variable length array ‘vla’ [-Wvla]
My questions are:
Why does the compiler accept that declaration?
The compiler cannot 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?
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.
A variable length array, which is a C99 feature, is an array of automatic storage duration whose length is determined at run time.
Variable length arrays is a feature where we can allocate an auto array (on stack) of variable size. It can be used in a typedef statement. C supports variable sized arrays from C99 standard.
The biggest problem is that one can not even check for failure as they could with the slightly more verbose malloc'd memory. Assumptions in the size of an array could be broken two years after writing perfectly legal C using VLAs, leading to possibly very difficult to find issues in the code.
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 [it]?
Precisely what the warning states it says about it: ISO C++ forbids variable length arrays.
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).
The standard requires that a conforming compiler must "issue a diagnostic" when it encounters something that is illegal. Having done that, it's free to continue to compile the code with an implementation-specific meaning. (Note that "with an implementation-specific meaning" is a polite form of "with undefined behavior").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With