According to the C++ Standard ([dcl.array])
In a declaration T D where D has the form
D1 [ constant-expressionopt ] attribute-specifier-seqopt
the size of an array must be constant (or not specified with an appropriate initializer).
However some compiler developers have elected to allow Variable Length Arrays (VLA) be it for programmer convenience, to maintain the ability to compile C code in C++ (C has allowed VLA since the C99 Standard), or some nefarious purpose that we may only learn after they have conquered the world.
The best standard compliant solution is to use a std::vector
when the size of the allocation cannot be known at compile time.
int n;
if (cin>>n) // don't allocate unless n is valid
{
vector<int> arr(n);
// use arr
}
Even if VLA is available, the vector
is still a safer solution. vector
is allocated from Dynamic storage, often a much larger data store than Automatic storage, and if the allocation fails an exception is thrown. The behaviour of a Variable Length Array that is too large for storage is often undefined and likely overflows the stack (a common form of Automatic storage), resulting in mystery bugs galore.
Allocating raw memory with new
should be avoided as it picks up additional management (it must be manually deleted at some point with delete[]
) and book-keeping (the size of the allocation is unknown to the pointer) responsibilities. The programmer may also now have to address The Rules of Three and Five.