Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable Length Array (VLA) in C++ compilers

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.

like image 860
BiagioF Avatar asked Sep 05 '16 16:09

BiagioF


People also ask

What is a variable length array in C?

A variable length array, which is a C99 feature, is an array of automatic storage duration whose length is determined at run time.

Does C allow variable length arrays?

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.

Why are variable length arrays bad in C?

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.


2 Answers

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).

like image 188
Lightness Races in Orbit Avatar answered Sep 27 '22 20:09

Lightness Races in Orbit


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").

like image 43
Pete Becker Avatar answered Sep 27 '22 19:09

Pete Becker