Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

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

What value does an enumeration object have if it is set to a value not equal to any of its respective enumeration constants?

Consider the following code:

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

enum foobar baz = 5;
enum foobar qux = 42;

The variable baz is set to the integer value 5, while the variable qux is set to the integer value 42.

I suspect the variable baz will hold the value BAR, but I'm unsure about the variable qux. No enumeration constant was assigned the value 42, so what happens when an enum foobar variable is set to such a value?

Is the C99 standard explicit about the outcome?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...