简体   繁体   English

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

[英]what happens when you create an array with non-const length in c++?

AFAIK this code is not a valid c++ code by standard: AFAIK此代码不是标准的有效c ++代码:

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? 我错了是编译器对我好吗?

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. 它被称为可变长度数组(VLA),标准C ++,任何版本的C ++都不允许这样做,尽管有些GCC支持它作为扩展。

If you're using GCC, then 如果您正在使用GCC,那么

  • Compile it with -pedantic option, you will see warning. -pedantic选项编译它,你会看到警告。
  • Compile it with -pedantic -Werror option, you will see warning turned into error. 使用-pedantic -Werror选项编译它,您将看到警告变为错误。

VLA is allowed only by C99, though not by other versions of C. VLA只允许通过C99,但不能通过其他版本的C.

The compiler is being nice. 编译器很好。 :) :)

It's actually part of the C standard, and some compilers (like GCC) extend C++ with this feature. 它实际上是C标准的一部分,一些编译器(如GCC)使用此功能扩展了C ++。

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. 这是C99标准可变长度数组(或VLA),许多可以编译C99的编译器,通常允许它的一些功能用于非标准的符合C ++代码。

G++ is one of these compilers, see here . G ++是这些编译器之一,请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 const到非const c ++ - const to non-const c++ C++中的const到非常量转换 - const to Non-const Conversion in C++ Const和非const c ++构造函数 - Const and non-const c++ constructor C ++ operator +和* non-const重载 - C++ operator + and * non-const overloading 当const方法是公共的并且非const方法受保护时,为什么C ++不会转换为const? - Why doesn't C++ cast to const when a const method is public and the non-const one is protected? 如果C ++类包含const引用和非const引用复制构造函数怎么办? - what if C++ class contains both const reference and non-const reference copy constructor? C ++重载运算符两次,一次返回非const引用和另一个const引用,有什么偏好? - C++ overload operator twice, one return non-const reference and the other const reference, what is the preference? C ++:如何根据上下文创建一个包含指针的常量或非常量临时对象? - C++: How to create a temporary object, containing a pointer - const or non-const, depending on context? C++ STL 中的 const_iterator 和非常量迭代器有什么区别? - What is the difference between const_iterator and non-const iterator in the C++ STL? 在C ++中定义和初始化非常量函数指针的静态常量数组 - Defining and initializing a static const array of non-const function pointers in C++
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM