orlp orlp - 1 year ago 73
C++ Question

Why doesn't C++ support dynamic arrays on the stack?

In C99 this was legal:

void f(size_t sz) {
char arr[sz];
// ...

However, this - dynamically sized stack arrays - has been dropped in C++, and not seeing a return in C++11.

AFAIK C++ was made with C compatibility in mind, so I wondered There must be some very good argument of not including this useful feature, right?

All I could think of was this:


  • Memory savings by allowing smarter array sizes that need to be on the stack (temporary buffers?).

  • Less "smart pointers" (or worse, manual bug-introducing
    delete []
    's) and slow heap allocations.

  • Compatibility with C99.


  • Allows people to easily allocate too large arrays on the stack giving hard-to-debug stack overflows.

  • More complicated for compiler writers.

So, why did they didn't they include it when they imported other C99 features?

To prevent this from being closed as "subjective" or "not constructive", I'm looking for quotes from commitee members or links to discussions talking about the matter - with bonus points for a quick SO roundup of course.

Rather than seeing this as a Ponies vs Hamsters discussion, see it as a historical question, mere interest in the advantages and disadvantages that were considered (if at all).

EDIT: As James McNellis pointed out in the comments below C++ existed before C99 standardized variable-length arrays. You might read my question then as: "Why didn't and won't they add it?".

Answer Source

I think, it's because C++ provides superior solutions: std::vector<T> and std::array<T,N> (C++11); though the latter is not dynamic as such but it's superior to raw arrays. You can always know the size, no matter which function you pass the vector or array.

Since C cannot provide these solutions, C99 came up with Variable Length Array (VLA). It has the same problem as regular arrays: it decays into a pointer on passing it to function, and you no longer know the size of the array.

And as Florian Weimer asked here at comp.std.c++ that if C++0x allows VLA, then what would the following code mean?

int vla[n]; //n is known at runtime!
std::vector<decltype(vla)> v; //what does this mean?

How is the compiler going to instantiate the vector template at compile-time when it's type argument depends on n which is known at runtime?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download