g ++:数组边界不是整数常量 [英] g++: array bound is not an integer constant

查看:476
本文介绍了g ++:数组边界不是整数常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用代码,

  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 ++ 会抱怨这个表达式吗?

解决方案

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

lockquote
整型常量表达式只能涉及文字(2.13),
枚举数, const 变量或整型或
的枚举类型的静态数据成员用常量表达式(8.5),
初始化的枚举类型非类型tem-积分或枚举类型的板参数,以及
sizeof 表达式。浮动文字(2.13.3)只有在
被转换为整数或枚举类型时才会出现。


您可以更改这:

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




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

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



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


一个整型常量表达式是一个字面常量表达式$

I think 2 * int b $ b $或$ unsignedd枚举类型。 (M_PI / rotationStep)+ 3 ,因此 N 符合新规则,但您的编译器可能尚未实现它们。

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?

解决方案

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.

这篇关于g ++:数组边界不是整数常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆