Why no variable size array in stack?

user695652 picture user695652 · Oct 18, 2011 · Viewed 9k times · Source

I don't really understand why I can't have a variable size array on the stack, so something like

foo(int n) {
   int a[n];
}

As I understand the stack(-segment) of part of the data-segment and thus it is not of "constant size".

Answer

Alok Save picture Alok Save · Oct 18, 2011

Variable Length Arrays(VLA) are not allowed in C++ as per the C++ standard.
Many compilers including gcc support them as a compiler extension, but it is important to note that any code that uses such an extension is non portable.

C++ provides std::vector for implementing a similar functionality as VLA.


There was a proposal to introduce Variable Length Arrays in C++11, but eventually was dropped, because it would need large changes to the type system in C++. The benefit of being able to create small arrays on stack without wasting space or calling constructors for not used elements was considered not significant enough for large changes in C++ type system.