用非常量变量声明数组大小 [英] Declaring the array size with a non-constant variable
问题描述
我一直认为在C++中声明数组时,大小必须是一个常量整数值.
I always thought that when declaring an array in C++, the size has to be a constant integer value.
例如:
int MyArray[5]; // correct
或
const int ARRAY_SIZE = 6;
int MyArray[ARRAY_SIZE]; // correct
但是
int ArraySize = 5;
int MyArray[ArraySize]; // incorrect
这里也是C++ 编程语言,由 Bjarne Stroustrup 解释的内容:
Here is also what is explained in The C++ Programming Language, by Bjarne Stroustrup:
数组元素的个数,数组绑定,必须是一个常量表达式(§C.5).如果您需要变量边界,请使用向量(第 3.7.1 节、第 16.3 节).例如:
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:
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!
这是我尝试使用 GCC v4.4.0 编译的内容:
Here is what I tried to compile using GCC v4.4.0:
void f(int i) {
int v2[i];
}
int main() {
int i = 3;
int v1[i];
f(5);
}
成功?!?
有什么我遗漏的吗?
推荐答案
这是 标准的 GCC 扩展:
您可以使用 -pedantic
选项使 GCC 发出警告,或使用 -std=c++98
使错误,当您使用一个这些扩展的一部分(以防便携性是一个问题).
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).
这篇关于用非常量变量声明数组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!