g++: array bound is not an integer constant

风流意气都作罢 提交于 2020-01-03 07:37:08

问题


With the code,

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

static unsigned int counts[N];

g++ gives the error:

array bound is not an integer constant before »]« token

I am using g++/gcc version 4.6.1

Can anybody tell me why g++ complains about the expression?


回答1:


As of the ISO C++ standard of 2003, that's not an integral constant-expression. Quoting section 5.19 of the standard:

An integral constant-expression can involve only literals (2.13), enumerators, const variables or static data members of integral or enumeration types initialized with constant expressions (8.5), non-type tem-plate parameters of integral or enumeration types, and sizeof expressions. Floating literals (2.13.3) can appear only if they are cast to integral or enumeration types.

You could change this:

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

to this:

const int inverseRotationStep = 1000;
const int N = 2*int(M_PI)*inverseRotationStep + 3;

(That's assuming M_PI is defined somewhere; it's not specified in the standard, but it's a common extension.)

The 2011 ISO C++ standard loosens this up a bit. 5.19p3 (quoting the N3337 draft) says:

An integral constant expression is a literal constant expression of integral or unscoped enumeration type.

I think 2*int(M_PI/rotationStep) + 3, and therefore N, qualifies under the new rules, but it's likely your compiler doesn't yet implement them.




回答2:


The problem is that...

g++ gives: array bound is not an integer constant before »]« token

A const value is not a constant expression (though its quite understandable why this would confuse you).

EDIT: I assumed C when I first read this. The problem here is that this expression is not being evaluated at compile time:

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

While this would be

const int N = 10;

As @ildjarn noted in the comments, floating point arithmetic is not guaranteed to be evaluated at compile time. Here is a related SO post I found.




回答3:


As Ed already pointed out, optimizations of floating point operations, including constant folding, are not guaranteed to happen at compile time. Intel's page on the subject gives a few examples, but mainly it's that the rounding behavior may be different and that floating point operations may throw exceptions. This paper goes a bit more in-depth (section 8.3, "Arithmetic Reduction").

GCC does only support

"floating-point expression contraction such as forming of fused multiply-add operations if the target has native support for them"

as mentioned in the description for the ffp-contract flag in the compiler optimizations manual.



来源:https://stackoverflow.com/questions/11269623/g-array-bound-is-not-an-integer-constant

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!