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在c++编程语言中解释的内容:
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 ?
我是不是漏掉了什么?
2 个解决方案
#1
24
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出错(考虑到可移植性)。
#2
6
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
#1
24
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出错(考虑到可移植性)。
#2
6
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