C++ 用非常量变量声明数组大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2863347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:19:05  来源:igfitidea点击:

Declaring the array size with a non-constant variable

c++arraysgcc

提问by Jér?me

I always thought that when declaring an array in C++, the size has to be a constant integer value.

我一直认为在C++中声明数组时,大小必须是一个常量整数值。

For instance :

例如 :

int MyArray[5]; // correct

or

或者

const int ARRAY_SIZE = 6;
int MyArray[ARRAY_SIZE]; // correct

but

int ArraySize = 5;
int MyArray[ArraySize]; // incorrect

Here is also what is explained in The C++ Programming Language, by Bjarne Stroustrup:

这也是Bjarne StroustrupThe C++ Programming Language 中解释的内容:

The number of elements of the array, the array bound, must be a constant expression (§C.5). If you need variable bounds, use a vector(§3.7.1, §16.3). For example:

数组元素的数量,数组绑定,必须是一个常量表达式(§C.5)。如果您需要变量边界,请使用向量(第 3.7.1 节、第 16.3 节)。例如:

void f(int i) { 
   int v1[i];          // error : array size not a constant expression
   vector<int> v2(i);  // ok 
} 

But to my big surprise, the code above does compile fine on my system !

但令我大吃一惊的是,上面的代码在我的系统上编译得很好!

Here is what I tried to compile :

这是我尝试编译的内容:

void f(int i) {
   int v2[i];
}

int main()
{
   int i = 3;
   int v1[i];
   f(5);
}

I got no error ! I'm using GCC v4.4.0.

我没有错误!我正在使用 GCC v4.4.0。

Is there something I'm missing ?

有什么我想念的吗?

回答by Dean Harding

This is a GCC extension to the standard: see here.

这是标准的 GCC 扩展:请参阅此处

You can use the -pedanticoption to cause GCC to issue a warning, or -std=c++98to make in an error, when you use one of these extensions (in case portability is a concern).

当您使用这些扩展之一时-pedantic,您可以使用该选项使 GCC 发出警告或-std=c++98出错(以防可移植性受到关注)。

回答by AraK

You are using a feature from C99 which is called VLA(variable length arrays). It would be better if you compile your program like this:

您正在使用 C99 中称为 VLA(可变长度数组)的功能。如果你这样编译你的程序会更好:

g++ -Wall -std=c++98 myprog.cpp