当你在 c++ 中创建一个非常量长度的数组时会发生什么?
AFAIK 按照标准,此代码不是有效的 C++ 代码:
int a = 5;
int b[a];
但似乎许多编译器都可以编译该代码(大部分带有警告),并且它的行为符合预期。我错了吗,编译器对我很好吗?
AFAIK this code is not a valid c++ code by standard:
int a = 5;
int b[a];
but it seems many compilers can compile that code (mostly with warning) and it just behaves as expected. Am I wrong is is it compilers being nice to me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它被称为可变长度数组 (VLA),标准 C++ 和任何版本的 C++ 都不允许它,尽管某些 GCC 支持将其作为扩展。
如果您使用 GCC,然后
-pedantic
选项编译它,您将看到警告。-pedantic -Werror
选项编译它,你会看到警告变成了错误。VLA 仅被 C99 允许,但其他版本的 C 不允许。
It is called variable length array (VLA) which is not allowed by Standard C++, any version of C++, though some GCC supports this as an extension.
If you're using GCC, then
-pedantic
option, you will see warning.-pedantic -Werror
option, you will see warning turned into error.VLA is allowed only by C99, though not by other versions of C.
编译器很好。 :)
它实际上是 C 标准的一部分,一些编译器(如 GCC)使用此功能扩展了 C++。
The compiler is being nice. :)
It's actually part of the C standard, and some compilers (like GCC) extend C++ with this feature.
这就是C99标准的Variable Length Array(或VLA),许多可以编译C99的编译器,通常允许在不符合标准的C++代码中使用它的一些功能。
G++ 是这些编译器之一,请参阅此处。
This is the C99 standards Variable Length Array (or VLA), many compilers that can compile C99, often allow some of its features to be used in non-standard conforming C++ code.
G++ is one of these compilers, see here.