C++ Standards Compliance – Why Variable Length Arrays Aren’t Dynamically Allocated

c++dynamic-arraysstandards-compliance

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?

Best Answer

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.

Related Question