This is because the C++ language does not have the C feature introduced in C99 known as "variable length arrays" (VLA).
C++ is lagging in adopting this C feature because the std::vector
type from its library fulfills most of the requirements.
Furthermore, the 2011 standard of C backpedaled and made VLA's an optional feature.
VLA's, in a nutshell, allow you to use a run-time value to determine the size of a local array that is allocated in automatic storage:
int func(int variable)
{
long array[variable]; // VLA feature
// loop over array
for (size_t i = 0; i < sizeof array / sizeof array[0]; i++) {
// the above sizeof is also a VLA feature: it yields the dynamic
// size of the array, and so is not a compile-time constant,
// unlike other uses of sizeof!
}
}
VLA's existed in the GNU C dialect long before C99. In dialects of C without VLA's, array dimensions in a declaration must be constant expressions.
Even in dialects of C with VLA's, only certain arrays can be VLA's. For instance static arrays cannot be, and neither can dynamic arrays (for instance arrays inside a structure, even if instances of that structure are allocated dynamically).
In any case, since you're coding in C++, this is moot!
Note that storage allocated with operator new
are not the VLA feature. This is a special C++ syntax for dynamic allocation, which returns a pointer type, as you know:
int *p = new int[variable];
Unlike a VLA's, this object will persist until it is explicitly destroyed with delete []
, and can be returned from the surrounding scope.