我使用的是 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/