BiagioF
BiagioF

Reputation: 9725

Why does my C++ compiler accept Variable Length Arrays (VLAs) if the feature is not standard?

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:

Upvotes: 23

Views: 6096

Answers (2)

Pete Becker
Pete Becker

Reputation: 76438

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

Upvotes: 6

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385274

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

Upvotes: 19

Related Questions