gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:33:47 25 4
gpt4 key购买 nike

说,我们有

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 notexplicitly specified, the underlying type of a scoped enumeration typeis 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 theenumerator values defined in the enumeration. (...) It is implementation-defined which integral type is used as the underlyingtype except that the underlying type shall not be larger than intunless the value of an enumerator cannot fit in an int or unsignedint.

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

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

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

您属于第二种情况,尽管您的代码可以在大多数编译器上运行,但最小位域的大小为 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 enumeratedtype.

所以基本上,它是一个 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 valuerepresentable as an int.

有以下限制:

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com