Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C++ support Variable Length Arrays?

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?

like image 803
Lightness Races in Orbit Avatar asked Dec 21 '11 17:12

Lightness Races in Orbit


People also ask

What is a variable length array in C?

In computer programming, a variable-length array (VLA), also called variable-sized or runtime-sized, is an array data structure whose length is determined at run time (instead of at compile time). In C, the VLA is said to have a variably modified type that depends on a value (see Dependent type).

Is array size fixed in C?

Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Does C store array size?

C does not store the size of the array - period. That is a fact of life. And, when an array is passed to a function, the size information is not passed to the function; the array 'decays' to a pointer to the zeroth element of the array - and only that pointer is passed.


2 Answers

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

like image 96
Johannes Schaub - litb Avatar answered Oct 18 '22 01:10

Johannes Schaub - litb


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.

like image 21
Lightness Races in Orbit Avatar answered Oct 18 '22 03:10

Lightness Races in Orbit