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

标签 c enums

我使用的是 gcc,我编译了这段代码,它应该会抛出一个错误,但它运行成功了。

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

int main(void) {
    enum DIRECTION currentDirection = 10;
    printf("%d\n",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.

虽然在 Annex I Common warnings 部分中它确实建议这样的警告,但不是必需的:

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 不会产生警告,尽管 clang 带有 -Wassign-enum 标志或 -Weverything 标志将会,它看起来类似于:

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

您可以使用 -Werror 使其成为错误。

Keith 提出了两个有趣的观察结果:

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

关于c - C 中的枚举不会在无效输入时引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21683289/

相关文章:

c# - 如何在 C# 中做标志

c - Saltzer 和 Kaashhoek 的《计算机系统设计原理》第 1 版第 100 页有错误吗?

从 Int 数组地址创建一个 Int 数组

c - Go中的递归链表类型别名

ios - 具有存储枚举的条件枚举开关

java - 是否可以将枚举属性的空值存储到数据库中?

c - SPI从机将数据读入stm32上的缓冲区?

c - 解决方案在 merge visual studio 2012 后不允许调试/构建/清理

c# - 通用可空枚举

algorithm - 如何枚举模式