c++ - 枚举变量的任意值

标签 c++ enums

有这段代码。

#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/

相关文章:

c++ - 创建不带参数的 sigc::slot

C++ - 枚举范围? Bjarne Stroustrup 书

java - 说 int 枚举模式是编译时常量是什么意思?

c++ - 为什么分配器常量在 vector 中?

c++ - 在 C++ 中创建非规范化(次规范化)浮点值

非固定枚举的 C++11 值?

c++ - 如何在 C++ 中按回车键执行代码?

javascript - 枚举成员如何在 TypeScript 中使用别名?

f# - 在有区别的联合上匹配

java - 继承公共(public)接口(interface)的枚举中的代码重复