有这段代码。
#include <iostream>
#include <climits>
enum e {zero,one};
void main()
{
e num=(e)INT_MAX;
std::cout<<num;
}
是否由标准定义输出为 2147483647?(条件 sizeof(int)=4 字节)
最佳答案
没有;将整数转换为枚举时,仅当整数值在范围内时才指定枚举值。来自标准:
7.2/10 An expression of arithmetic or enumeration type can be converted to an enumeration type explicitly. The value is unchanged if it is in the range of enumeration values of the enumeration type; otherwise the resulting enumeration value is unspecified.
其中“范围”在 7.2/7 中以相当复杂的方式描述,基本上上升到 2^M-1
的最小值,该值不小于最大定义值。
编译器可以使用任何整数类型来表示枚举,只要它大到足以容纳所有的枚举值;所以在这种情况下,可以随意使用比 int
更小的类型,例如 char
。此外,INT_MAX
只能保证至少为 32767。
关于c++ - 枚举变量的任意值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8800926/