为什么C ++允许不动态分配的可变长度数组? [英] Why does C++ allow variable length arrays that aren't dynamically allocated?

查看:269
本文介绍了为什么C ++允许不动态分配的可变长度数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C ++比较陌生,从一开始,我就钻进了你不能做的事情。

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];

而是必须使用动态内存。但是,我最近发现上面的编译(虽然我得到一个非常警告说它被ISO C ++禁止)。我知道,如果标准不允许,这显然是一个坏主意,但我以前甚至不知道这是可能的。

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.

我的问题是,为什么g ++允许不动态分配的可变长度数组,如果标准不允许的话?

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?

推荐答案

如果编译器可以这么做,为什么

支持可变长度数组(VLA)添加到C99中的C语言。

Support for variable length arrays (VLAs) was added to the C language in C99.

很可能是因为对它们的支持存在于gcc(支持C99) ,它是相对直接地添加支持他们到g ++。

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.

这篇关于为什么C ++允许不动态分配的可变长度数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆