使用这段代码,
const double rotationStep = 0.001;
const int N = 2*int(M_PI/rotationStep) + 3;
static unsigned int counts[N];
g++
出现以下错误信息:
数组边界在 »]« 符号之前不是一个整数常量
我正在使用 g++
/gcc
版本 4.6.1。
有谁能告诉我为什么 g++
抱怨这个表达式?
const double rotationStep = 0.001;
const int N = 2*int(M_PI/rotationStep) + 3;
转换为:
const int inverseRotationStep = 1000;
const int N = 2*int(M_PI)*inverseRotationStep + 3;
M_PI
已经被定义; 尽管它没有在标准中规定,但它是一种常见的扩展。)我认为整数常量表达式是整数或非作用域枚举类型的文字常量表达式。
2*int(M_PI/rotationStep) + 3
,因此N
符合新规则,但你的编译器可能还没有实现它们。问题在于...
g++ gives: array bound is not an integer constant before »]« token
const
值不是常量表达式(尽管可以理解为什么会让你感到困惑)。const int N = 2*int(M_PI/rotationStep) + 3;
虽然这可能会
const int N = 10;
正如评论中@ildjarn所指出的,浮点运算不能保证在编译时被计算。这里是我找到的相关SO帖子。
static
关键字,它应该可以编译而不会出现警告。 - higuaroconst
声明中的浮点数部分是实现定义的部分,还是声明中使用了static
关键字? - higuarog++ -pedantic
编译。我得到了“warning: ISO C++ forbids variable length array ‘counts’ [-Wvla]”的警告。(默认情况下,g++不符合标准。) - Keith Thompson
static
关键字从您的代码中删除并重新编译吗? - higuaro