加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C中的枚举不会在无效输入上引发错误

发布时间:2020-12-16 09:50:26 所属栏目:百科 来源:网络整理
导读:我正在使用 gcc,我编译了这段代码,它应该抛出一个错误,但它运行成功. enum DIRECTION {EAST,WEST,NORTH,SOUTH};int main(void) { enum DIRECTION currentDirection = 10; printf("%dn",currentDirection); return 0;} 输出: 10 解决方法 枚举类型在 C99 dr
我正在使用 gcc,我编译了这段代码,它应该抛出一个错误,但它运行成功.

enum DIRECTION {EAST,WEST,NORTH,SOUTH};

int main(void) {
    enum DIRECTION currentDirection = 10;
    printf("%dn",currentDirection);
    return 0;
}

输出:
10

解决方法

枚举类型在 C99 draft standard部分中定义6.7.2.2枚举说明符为:

Each enumerated type shall be compatible with char,a signed integer type,or an
unsigned integer type. The choice of type is implementation-defined,110) […]

脚注110说:

An implementation may delay the choice of which integer type until all enumeration constants have been seen.

该标准并未说明您不允许指定枚举声明中指定值之外的值,尽管在附录I中的常见警告中它确实提出了这样的警告,但并不要求:

A value is given to an object of an enumerated type other than by assignment of an
enumeration constant that is a member of that type,or an enumeration object that has
the same type,or the value of a function that returns the same enumerated type (6.7.2.2).

gcc不会产生警告,虽然使用-Wassign-enum标志或-Weverything标志,但它看起来与此类似:

warning: integer constant not in range of enumerated type ‘enum DIRECTION’ [-Wassign-enum]

并且您可以使用-Werror使其成为错误.

基思提出了两个有趣的观察:

>使用-Werror会使clang不符合,因为代码有效C.> enum DIRECTION currentDirection = 128;具有实现定义的行为,因为类型很可能是char.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读