I'm relatively new to C++, and from the beginning it's been drilled into me that you can't do something like
int x;
cin >> x;
int array[x];
Instead, you must use dynamic memory. However, I recently discovered that the above will compile (though I get a -pedantic warning saying it's forbidden by ISO C++). I know that it's obviously a bad idea to do it if it's not allowed by the standard, but I previously didn't even know this was possible.
My question is, why does g++ allow variable length arrays that aren't dynamically allocated if it's not allowed by the standard? Also, if it's possible for the compiler to do it, why isn't it in the standard?
Support for variable length arrays (VLAs) was added to the C language in C99.
It's likely that since support for them exists in gcc (to support C99), it was relatively straightforward to add support for them to g++.
That said, it's an implementation-specific language extension, and it's not a good idea to use implementation-specific extensions if you want your code to be portable.
Because it's supported in C99. I can't really speak to why it's not in the C++ standard. However, it's not as useful as you might think because it easily leads (if you're not careful) to stack overflow (since it's typically based on alloca, itself non-standard). Another mistake is to return a pointer to a dynamic array, which will immediately go out of scope.
Lot's of compilers embrace and extend standards. There are two basic reasons:
- Nefarious compiler-writers probably think that making it harder to move away from their compiler helps increase longevity.
- Benevolent compiler-writers probably think that giving you more options when they can at little to no cost to themselves is a good thing.
All of the reasons mentiond having to do with them being in C are correct, though there are limitations for the requirement. You're example may demonstrate more flexible support than what is required in C (if you implemented that using scanf rather than cin, put it in a .c file, and used gcc).
This is almost just a implicit call to alloca (allocate auto) which just decreases the stack pointer (increasing the stack size) and copies the new stack pointer to another register which is used as a pointer to the allocated memory.
The difference is that constructors and destructors aren't going to be called on objects created with a alloca.
来源:https://stackoverflow.com/questions/2610449/why-does-c-allow-variable-length-arrays-that-arent-dynamically-allocated