g ++:数组绑定不是整数常量

use*_*269 9 c++ g++ constants

有了代码,

const double rotationStep = 0.001;
const int N = 2*int(M_PI/rotationStep) + 3;

static unsigned int counts[N];
Run Code Online (Sandbox Code Playgroud)

g++ 给出错误:

数组绑定在»]«标记之前不是整数常量

我正在使用g++/ gcc版本4.6.1

谁能告诉我为什么g++抱怨这个表达?

Kei*_*son 7

从2003年的ISO C++标准来看,这不是一个完整的常量表达式.引用标准第5.19节:

一个积分常数表达式可以只涉及文字(2.13),统计员,const变量或常量表达式(8.5),积分或枚举类型的非类型TEM-板参数,并初始化积分或枚举类型的静态数据成员 sizeof表达式.浮动文字(2.13.3)只有在转换为整数或枚举类型时才会出现.

你可以改变这个:

const double rotationStep = 0.001;
const int N = 2*int(M_PI/rotationStep) + 3;
Run Code Online (Sandbox Code Playgroud)

对此:

const int inverseRotationStep = 1000;
const int N = 2*int(M_PI)*inverseRotationStep + 3;
Run Code Online (Sandbox Code Playgroud)

(假设M_PI是在某处定义的;它没有在标准中指定,但它是一个常见的扩展.)

2011 ISO C++标准略微放松了这一点.5.19p3(引用N3337草案)说:

一个积分常量表达式是整体的或无作用域枚举类型的字面常量表达式.

认为 2*int(M_PI/rotationStep) + 3,因此N,符合新规则,但很可能你的编译器还没有实现它们.