Enumeration object set to a value not equal to any of its respective enumeration constants

拜拜、爱过 提交于 2019-11-28 13:39:42

The C99 draft standard does not seem to restrict an enumerator to take on values of its members exclusively but it does say that the enumerators underlying type shall be capable of representing the values of all its members. This is covered in section 6.7.2.2 Enumeration specifiers:

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

and so you will be relying on implementation defined behavior if you use a value greater then the members define. In the case of signed integer overflow leads to undefined behavior as per section 5 which says:

If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined.

Typically we see enums being assigned values outside of those specified by their members when they are used to represent bit fields.

Variable qux is not going to hold any of the enums values. Its value will be equal to 42 in the underlying type the compiler selects to represent foobar, which is implementation-defined. This would not present a problem when the value is 42, but it may become an issue when the constant does not fit in the type selected by the compiler for your enumeration.

One of the reasons why the compiler allows assignments of values other than enum constants is to support "flag" enumerations, when constants are expected to be combined in bitwise operations:

enum foobar {
    foo = 1
,   bar = 2
,   baz = 4
} test = (foo | baz);

Variable test above holds the value of 5, which does not correspond to any of the enum constants.

enum foobar{
    FOO = 1,
    BAR = 5
};

enum foobar baz = 5;

the baz declaration is equivalent to:

enum foobar baz = BAR;

as BAR is an int of value 5.

This declaration is also valid:

enum foobar qux = 42;

C says an enum type is an integer type sufficiently large to represent all its enum constants. If the enum type is not sufficiently large, the value is converted to the enum integer type as for every integer type as per the rules of integer conversion (c99, 6.3.1.3). This integer conversion can be implementation-defined (see 6.3.1.3p3).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!