Reputation: 423
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?
Upvotes: 9
Views: 14358
Reputation: 1866
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.
Upvotes: 1
Reputation: 263197
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, andsizeof
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.
Upvotes: 7
Reputation: 124632
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.
Upvotes: 4