如果枚举不能装入无符号整型,会发生什么情况?
What happens if an enum cannot fit into an unsigned integral type?
正如Bathsheba所要求的,并作为"如果enum不能适合整型会发生什么?"的后续问题。:
假定enum定义如下:
enum foo : unsigned int
{
bar = UINT_MAX,
oops
};
oops
的值是否有定义?
MSVS2015编译:
warning C4340: 'oops': value wrapped from positive to negative value
warning C4309: 'initializing': truncation of constant value
warning C4369: 'oops': enumerator value '4294967296' cannot be represented as 'unsigned int', value is '0'
MSVS2015输出:
bar = 4294967295
oops= 0
gcc 4.9.2编译:
9 : note: in expansion of macro 'UINT_MAX'
bar = UINT_MAX,
^
10 : error: enumerator value 4294967296l is outside the range of underlying type 'unsigned int'
oops
^
Compilation failed
gcc 4.9.2 output
//compilation failed
这是一个非常有趣的问题。简单的答案是,这是字面上未定义的:标准没有说任何关于这种情况。
有一个更好的例子,考虑以下enum
:
enum foo : bool { True=true, undefined };
按标准:
dcl。enum) /:[…没有初始化式的枚举数定义将前一个枚举数的值加1后得到的值赋给枚举数。
因此,本例中foo::undefined
的值为2
(true+1
)。不能表示为bool
.
是病态的吗?
否,根据标准,它是完全有效的,只有非固定底层类型有不能表示所有枚举数值的限制:
dcl。enum]/7:对于底层类型不固定的枚举,[…]如果没有整型可以表示所有枚举数的值,则该枚举是病态的。
它没有说明固定的底层类型不能表示所有枚举数的值。
原题oops
和undefined
的值是多少?
It is undefined:标准没有说明这种情况
foo::undefined
的可能取值:
- 最高可能值(
true
):undefined
和oops
应该是底层类型的最大值。 - 最低可能值(
false
): 底层类型的最小值。注意:在有符号整数中,它将不匹配整数溢出的当前行为(未定义行为)。 - 随机值(?):编译器将选择一个值
所有这些值的问题是,它可能导致两个字段具有相同的值(例如foo::True == foo::undefined
)。
undefined=2
)和"隐式"初始化式(如True=true, undefined
)的区别按标准:
dcl。enum]/5:如果基础类型是固定的,则右括号之前的每个枚举数的类型都是基础类型,并且枚举数定义中的常量表达式应是基础类型的转换常量表达式。
换句话说:
enum bar : bool { undefined=2 };
等价于
enum bar : bool { undefined=static_cast<bool>(2) };
则bar::undefined
将是true
。在"隐式"初始化式中,情况并非如此:本标准段落只说明初始化式,而不是"隐式"初始化式。
- 通过这种方式,具有固定底层类型的
- 标准未定义其值
enum
可能具有不可表示的值。根据问题和评论,这在GCC和clang中无效,但在MSVS-2015中有效(带有警告)。
- C 字符串返回字符串的整数/双精度/长整型值
- 是什么导致了这种使用三进制而不是短整型的有符号int到无符号int转换
- 无法在 Arduino 中uint8_t数组转换为无符号长整型数组
- 将指针分配给另一个指针时会发生什么情况?
- 在什么情况下,两个堆栈分配的结构对象的 this 点指向同一个地址?
- 在什么情况下,我想在 C/C++ 代码中使用内联汇编代码
- 发生注入类名时会发生什么情况?(C++)
- 在什么情况下,需要共享智能指针而无法使用唯一指针?
- 重新分配向量时,向量中的内存会发生什么情况
- JNI 日期值转换问题,在C++中获取不同的长整型值
- 如果结构中的字符串比使用的 p/调用签名长或短,会发生什么情况?
- 无符号长整型和无符号 int 之间有什么区别,这 2 种类型应该如何在 c# 中封送?
- 是否存在将长整型转换为指针有效的情况
- 计算机中的字长与整型或长有什么关系?
- 如果枚举不能装入无符号整型,会发生什么情况?
- 如果枚举不能装入整型,会发生什么情况?
- 当不同类型的整型操作数的==运算符的值为true时,我什么时候才能确定这些操作数是真正相等的
- 什么是整型数对的快速哈希函数?
- c++中计算long long int型整型的绝对值最快的方法是什么?
- 在C++中,用十六进制或八进制表示的整型文字的默认类型是什么