Why does C++ allow variable length arrays that are

2019-01-08 01:28发布

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?

4条回答
孤傲高冷的网名
2楼-- · 2019-01-08 02:08

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.

查看更多
神经病院院长
3楼-- · 2019-01-08 02:18

Lot's of compilers embrace and extend standards. There are two basic reasons:

  1. Nefarious compiler-writers probably think that making it harder to move away from their compiler helps increase longevity.
  2. Benevolent compiler-writers probably think that giving you more options when they can at little to no cost to themselves is a good thing.
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-08 02:19

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.

查看更多
倾城 Initia
5楼-- · 2019-01-08 02:33

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.

查看更多
登录 后发表回答