Why no variable size array in stack?

后端 未结 7 1212
南方客
南方客 2020-11-27 19:28

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 underst

7条回答
  •  广开言路
    2020-11-27 20:00

    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.

提交回复
热议问题