枚举可以容纳大于 INT_MAX 的无符号整数吗?

标签 c enums unsigned-integer

enum Some_Flag {
        SOME_FLAG_A = 0x00000000u,
        SOME_FLAG_B = 0x00000001u,
        SOME_FLAG_C = 0x00000002u,
        /* ... */
        SOME_FLAG_Z = 0x80000000u,
};

uint32_t a;
a = SOME_FLAG_Z;

假设 32 位整数... 这在 C 中有效吗?

这个标准对我来说似乎模棱两可。

编辑:

引用标准:

6.4.4.3 Enumeration constants

Semantics

2 An identifier declared as an enumeration constant has type int. Forward references: enumeration specifiers (6.7.2.2).

6.7.2.2 Enumeration specifiers

Constraints

2 The expression that defines the value of an enumeration constant shall be an integer constant expression that has a value representable as an int.

Semantics

3 The identifiers in an enumerator list are declared as constants that have type int and may appear wherever such are permitted.127) An enumerator with = defines its enumeration constant as the value of the constant expression. If the first enumerator has no =, the value of its enumeration constant is 0. Each subsequent enumerator with no = defines its enumeration constant as the value of the constant expression obtained by adding 1 to the value of the previous enumeration constant. (The use of enumerators with = may produce enumeration constants with values that duplicate other values in the same enumeration.) The enumerators of an enumeration are also known as its members.

4 Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined,128) but shall be capable of representing the values of all the members of the enumeration. The enumerated type is incomplete until immediately after the } that terminates the list of enumerator declarations, and complete thereafter.

C11 draft

约束似乎清楚地表明枚举是一个整数,但 6.7.2.2_4 似乎允许无符号整数 ¿?

最佳答案

您的代码无效:

C90(6.5.2.2,枚举说明符):

Constraints

The expression that defines the value of an enumeration constant shall be an integral constant expression that has a value representable as an int.

C99(在 C11 草案中未更改)(6.7.2.2,枚举说明符):

Constraints

  1. The expression that defines the value of an enumeration constant shall be an integer constant expression that has a value representable as an int.

您的值超出了 32 位 int 的范围,因此这是一个错误(需要进行诊断)。

请注意,这完全是关于枚举常量的“初始化器”。例如,如果我们有

enum foo { BAR = 42u };

然后这个约束说明值 42u 必须能够放入 int(确实如此;它只是一个无符号的 42,而 42 适合一个 int).

BAR 本身的类型是int(令人惊讶的是,不是enum foo)。

但是如果你声明一个类型为 enum foo 的变量,那么它的大小和符号是实现定义的。它将基于一些现有的整数类型(可以存储所有枚举值),但实际使用的类型可能因实现而异(以及不同的 enum 类型)。

关于枚举可以容纳大于 INT_MAX 的无符号整数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53681947/

相关文章:

python - 使用枚举定义 Python 类

c - 为什么 C 隐式转换像它们那样运行?

C++无符号无限循环比较错误

c - unsigned 和 unsigned int 有区别吗

c - 在c中分配给指向字符串的索引解引用指针时出现段错误

javascript - 为什么 TypeScript 转译器将枚举编译成字典查找而不是简单的对象?

c - Lua调用C函数的性能

C11 - 通用选择中的枚举

c - 反转双向链表问题

c - 将 Vala 与 C 结合使用时出现内存泄漏