【发布时间】:2022-03-10 12:28:23
【问题描述】:
来自 C++ 文档http://www.cplusplus.com/doc/tutorial/arrays/
要定义像 int a[b]; 这样的数组,变量 b 必须是常量。
这是我在 g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3 下运行的内容
int main(){
int a = 10;
int b[a];
for(int i = 0; i < 10; i++){
cout << b[i] << endl;
}
return 0;
}
变量a 不是常量,我没有错误。请问从什么版本的g++开始会接受这种数组定义?
【问题讨论】:
-
好吧,在这种情况下,我希望编译器优化
a,这样您实际上就可以使用常量进行初始化。尝试使用rand()/100000进行初始化,看看会发生什么 (#include <cstdlib>) -
@MattPhillips 怀疑,优化器是在那之后很久才出现的。
-
@MattPhillips:优化不应该是相关的。语言规则需要一个常量表达式,而这只是意味着编译器能够在编译时弄清楚如何计算。