GCC不支持简单的整型常量表达式? [英] GCC doesn't support simple integer constant expression?

查看:189
本文介绍了GCC不支持简单的整型常量表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

GCC 4.9和5.1 拒绝这个简单的C99声明在全球范围内。 Clang接受它。

  const int a = 1,b = a; //错误:初始化元素不是常量

这样一个基本特征怎么会丢失?它看起来非常简单。

解决方案

C99 1 section 6.6常量表达式是控制部分。它在小节 6 7


<6>整数常量表达式应该具有整数类型,并且只应具有 整数常量,枚举常量,字符常量,sizeof表达式的结果为整数常量的常量和浮点常量是演员的直接操作数



在整型常量表达式中演员操作符只能将算术类型转换为整数类型,

整数和浮点常量的定义在 6.4.4中指定标准,它仅限于实际的值<文字>而不是变量。


7初始化器中的常量表达式允许更多的纬度。 (a)算术常量表达式,(b)空指针常量,(c)地址常量或(d)地址对象类型的常量加或减一个整型常量表达式


由于 6 7 中的 none

因此,真正的问题并不是为什么 gcc 拒绝它,但是为什么 clang 接受它,并且似乎被埋在同一小节 10 中部分:


10 /实现 可以 接受其他形式的常量表达式。

换句话说,标准规定了必须允许常量表达式的含义,但不限制IM只允许






1 C11很多除了允许 _Alignof 以及 sizeof 之类的小事外,同样的事情。


GCC 4.9 and 5.1 reject this simple C99 declaration at global scope. Clang accepts it.

const int a = 1, b = a; // error: initializer element is not constant

How could such a basic feature be missing? It seems very straightforward.

解决方案

C991 section 6.6 Constant expressions is the controlling section. It states in subsections 6 and 7:

6/ An integer constant expression shall have integer type and shall only have operands that are integer constants, enumeration constants, character constants, sizeof expressions whose results are integer constants, and floating constants that are the immediate operands of casts.

Cast operators in an integer constant expression shall only convert arithmetic types to integer types, except as part of an operand to the sizeof operator.

The definition of integer and floating point constants is specified in 6.4.4 of the standard, and it's restricted to actual values (literals) rather than variables.

7/ More latitude is permitted for constant expressions in initializers. Such a constant expression shall be, or evaluate to, one of the following (a) an arithmetic constant expression, (b) a null pointer constant, (c) an address constant, or (d) an address constant for an object type plus or minus an integer constant expression.

Since a is none of those things in either subsection 6 or 7, it is not considered a constant expression as per the standard.

The real question, therefore, is not why gcc rejects it but why clang accepts it, and that appears to be buried in subsection 10 of that same section:

10/ An implementation may accept other forms of constant expressions.

In other words, the standard states what an implementation must allow for constant expressions but doesn't limit implementations to allowing only that.


1 C11 is much the same other than minor things like allowing _Alignof as well as sizeof.

这篇关于GCC不支持简单的整型常量表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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