我一直认为在C++中声明数组时,大小必须是一个常量整数值。
例如:
int MyArray[5]; // correct
或者
const int ARRAY_SIZE = 6;
int MyArray[ARRAY_SIZE]; // correct
但是
int ArraySize = 5;
int MyArray[ArraySize]; // incorrect
这也是在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:
void f(int i) { int v1[i]; // error : array size not a constant expression vector<int> v2(i); // ok }
但是让我大吃一惊的是,上面的代码在我的系统上竟然编译通过了!
以下是我使用GCC v4.4.0尝试编译的代码:
void f(int i) {
int v2[i];
}
int main() {
int i = 3;
int v1[i];
f(5);
}
成功?!?
我有什么遗漏的吗?