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
Declaring the array size with a non-constant variable
提问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 Stroustrup在The 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 -pedantic
option to cause GCC to issue a warning, or -std=c++98
to 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