使用非常量变量声明数组大小

31

我一直认为在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);
}

成功?!?

我有什么遗漏的吗?


18
这就是为什么只是用编译器测试并不能证明代码的正确性。 - GManNickG
2
不需要动态分配内存,在运行时C/C++数组大小可以被允许吗? - nico
2个回答

32
这是标准的GCC扩展之一:
您可以使用-pedantic选项使GCC发出警告,或者使用-std=c++98将其视为错误,当您使用其中一个扩展时(以确保可移植性)。

1
使用-std=c++98并不能帮助,它并不会禁用扩展。使用-pedantic来获得警告或者使用-pedantic-errors来获得错误。 - Jonathan Wakely

6

您正在使用C99中的一个称为VLA(可变长度数组)的功能。如果您按照以下方式编译程序会更好:

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

为什么这样会更好呢?它并没有改变任何东西。 - Jonathan Wakely

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接