Does C++ support Variable Length Arrays?

2019-01-01 07:37发布

问题:

No, wait, bear with me...

VLAs were always a GCC extension, but they were adopted by C99:

[C99: 6.7.5.2/4]: If the size is not present, the array type is an incomplete type. If the size is * instead of being an expression, the array type is a variable length array type of unspecified size, which can only be used in declarations with function prototype scope; such arrays are nonetheless complete types. If the size is an integer constant expression and the element type has a known constant size, the array type is not a variable length array type; otherwise, the array type is a variable length array type.

C99 is also known as ISO/IEC 9899:1999.

Now:

[C++11: 1.1/2]: C++ is a general purpose programming language based on the C programming language as specified in ISO/IEC 9899:1999 (hereinafter referred to as the C standard). In addition to the facilities provided by C, C++ provides additional data types, classes, templates, exceptions, namespaces, operator overloading, function name overloading, references, free store management operators, and additional library facilities.

So shouldn\'t C++11 have VLAs too?

回答1:

That leeway wording doesn\'t mean that any and everything in C99 is in C++11. What you quoted is just introductory text.



回答2:

This C99 feature is effectively overridden by C++\'s own semantics, as can be any otherwise \"inherited\" feature:

[C++11: 8.3.4/1]: In a declaration T D where D has the form

D1 [ constant-expressionopt ] attribute-specifier-seqopt

[..]

This is the only array declaration syntax we\'re given in C++.

Note that no mention of this difference is given in the \"compatibility with C\" clause C.1.



回答3:

The definition of constant-expression is different for the two languages.

const size_t size = 5;
int array[size]; // array in C++, VLA in C


回答4:

This compiles for me: (g++ 4.6 with -std=c++0x). But it doesn\'t compile with -pedantic (thanks @MarkB). Instead it warns that \"template.cpp:7:12: warning: ISO C++ forbids variable length array ‘n’ [-Wvla]\"

int main(int argc, char ** argv) {
    int n[argc];
}

So the size of n can not be known at compile time by the compiler. Is this a GNU extension to C++? This does appear to be a GNU extension, and that VLAs are not an official part of C++11.

(Of course, I\'m just playing with a compiler. So take this with a pinch of salt.)