C99 / C11
前奏:
5.2.4.2.1 要求int 至少 16 位宽; AFAIK 没有上限(long 必须更长或等于 6.2.5 /8)。
6.5 /5:
如果在计算表达式期间出现异常情况(即,如果结果未在数学上定义或不在其类型的可表示值范围内),则行为未定义。
如果你的 `int` 是 32 位宽(或更少)
那么 OP 中的示例违反了约束 6.7.2.2 /2:
定义枚举常量值的表达式应为整数
具有可表示为 int 的值的常量表达式。
此外,枚举数被定义为int类型的常量,6.7.2.2 /3:
枚举器列表中的标识符被声明为类型为int 和
可以出现在任何允许的地方。
注意,枚举的类型和枚举数/枚举常量的类型是有区别的:
enum foo { val0 };
enum foo myVariable; // myVariable has the type of the enumeration
uint_least8_t v = val0*'c'; // if val0 appears in any expression, it has type int
在我看来,这允许缩小范围,例如将枚举 type 的大小减小到 8 位:
enum foo { val1 = 1, val2 = 5 };
enum foo myVariable = val1; // allowed to be 8-bit
但它似乎不允许扩大,例如
enum foo { val1 = INT_MAX+1 }; // constraint violation AND undefined behaviour
// not sure about the following, we're already in UB-land
enum foo myVariable = val1; // maximum value of an enumerator still is INT_MAX
// therefore myVariable will have sizeof int
枚举数自动递增
由于 6.7.2.2 /3,
[...] 每个没有= 的后续枚举数都将其枚举常量定义为constant 表达式的值,该表达式通过将1 与前一个枚举常量的值相加而获得。 [...]
示例结果为 UB:
enum foo {
val0 = INT_MAX,
val1 // equivalent to `val1 = INT_MAX+1`
};