I was having trouble understanding why
int n;
cin>>n;
int arr[n];
works. I was told that this code should not run because the value of 'n' could only be declared during runtime and therefore should not compile. I was also told that my 'n' variable should be constant. How do you make it constant when there is a 'cin>>' (Im having trouble understanding how to fit in a constant).I know the code is rather simple, but I'm conflicted because of what I was told.
According to the C++ Standard ([dcl.array])
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.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 withdelete[]
) 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.