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

can an enum hold unsigned integers greater than INT_MAX?

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 类型)。