c++ - 是否允许枚举具有未列出的值?

标签 c++ c enums language-lawyer

说,我们有

enum E
{
  Foo = 0,
  Bar = 1
};

现在,我们开始了

enum E v = ( enum E ) 2;

然后

switch ( v )
{
  case Foo:
    doFoo();
  break;
  case Bar:
    doBar();
  break;
  default:
    // Is the compiler required to honor this?
    doOther();
  break;
}

由于上面的开关处理枚举的每个可能列出的值,编译器是否允许优化掉上面的 default 分支,或者在值的情况下具有未指定或未定义的行为的枚举不在列表中?

我期望 C 和 C++ 的行为应该是相似的,所以问题是关于这两种语言的。但是,如果在这种情况下 C 和 C++ 之间存在差异,那么也很高兴知道这一点。

最佳答案

C++情况

在 C++ 中,每个枚举都有一个基础的整数类型。如果明确指定(例如:enum test2 : long { a,b};)或者如果是 int,则它可以是固定的默认情况下是 scoped 枚举(例如:enum class test { a,b };):

[dcl.enum]/5: Each enumeration defines a type that is different from all other types. Each enumeration also has an underlying type. (...) if not explicitly specified, the underlying type of a scoped enumeration type is int. In these cases, the underlying type is said to be fixed.

对于底层类型未明确固定的 unscoped 枚举(您的示例),该标准为您的编译器提供了更大的灵 active :

[dcl.enum]/7: For an enumeration whose underlying type is not fixed, the underlying type is an integral type that can represent all the enumerator values defined in the enumeration. (...) It is implementation-defined which integral type is used as the underlying type except that the underlying type shall not be larger than int unless the value of an enumerator cannot fit in an int or unsigned int.

现在是非常棘手的事情:枚举变量可以保存的值取决于底层类型是否固定:

  • 如果是固定的,"枚举的值就是 基础类型。”

  • 否则,最小位域的最小值和最大值内的整数值可以容纳最小的枚举数和最大的枚举数。

您属于第二种情况,尽管您的代码可以在大多数编译器上运行,但最小位域的大小为 1,因此您可以在所有兼容的 C++ 编译器上确定的唯一值是 0 到 1 之间的值。 ..

结论:如果你想确保该值可以设置为 2,你要么必须让你的枚举成为一个作用域枚举,要么显式指明一个底层类型。**

更多阅读:

C情况

C的情况要简单得多(C11):

6.2.5/16: An enumeration comprises a set of named integer constant values. Each distinct enumeration constitutes a different enumerated type.

所以基本上,它是一个 int:

6.7.2.2./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.

有以下限制:

Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined, but shall be capable of representing the values of all the members of the enumeration.

关于c++ - 是否允许枚举具有未列出的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33812998/

相关文章:

c++ - Apache 交叉编译错误./gen_test_char : cannot execute binary file

c++ - 如何在循环后立即打断点?

c++ - 将共享指针设置为空

c - 如何从 C 中作为结构成员的指针访问数组中的值

c - printf 在 for 循环中打印更多行

java - 当在复合键中使用时,JPA AttributeConverter 在 Spring-data/hibernate 查询中不被接受

c++ - 获取图像中的最外边缘

c - 将int数组在内存中的新空间重新分配为0

java - 枚举设计决策的常量特定方法

c# - C# 和 VB.NET 中枚举的区别