当你在 c++ 中创建一个非常量长度的数组时会发生什么?

发布于 2024-12-17 17:16:28 字数 141 浏览 0 评论 0原文

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技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

余生再见 2024-12-24 17:16:28

它被称为可变长度数组 (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

  • Compile it with -pedantic option, you will see warning.
  • Compile it with -pedantic -Werror option, you will see warning turned into error.

VLA is allowed only by C99, though not by other versions of C.

反目相谮 2024-12-24 17:16:28

编译器很好。 :)

它实际上是 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.

满意归宿 2024-12-24 17:16:28

这就是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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文