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
303 views
in Technique[技术] by (71.8m points)

c++ - Enum variable default value?

The question is simple:

#include <iostream>

enum SomeEnum {  
    EValue1 = 1,  
    EValue2 = 4
};

int main() {
    SomeEnum enummy;
    std::cout << (int)enummy;
}

What will be the output?

Note: This is not an interview, this is code inherited by me from previous developers. Streaming operator here is just for example, actual inherited code doesn't have it.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The program has Undefined Behavior. The value of enummy is indeterminate. Conceptually there is no difference between your code and the following code:

int main() {
   int i;          //indeterminate value
   std::cout << i; //undefined behavior
};

If you had defined your variable at namespace scope, it would be value initialized to 0.

enum SomeEnum {  
    EValue1 = 1,  
    EValue2 = 4,  
};
SomeEnum e; // e is 0
int i;      // i is 0

int main()
{
    cout << e << " " << i; //prints 0 0 
}

Don't be surprised that e can have values different from any of SomeEnum's enumerator values. Each enumeration type has an underlying integral type(such as int, short, or long) and the set of possible values of an object of that enumeration type is the set of values that the underlying integral type has. Enum is just a way to conveniently name some of the values and create a new type, but you don't restrict the values of your enumeration by the set of the enumerators' values.

Update: Some quotes backing me:

To zero-initialize an object of type T means:
— if T is a scalar type (3.9), the object is set to the value of 0 (zero) converted to T;

Note that enumerations are scalar types.

To value-initialize an object of type T means:
— if T is a class type blah blah
— if T is a non-union class type blah blah
— if T is an array type, then blah blah — otherwise, the object is zero-initialized

So, we get into otherwise part. And namespace-scope objects are value-initialized


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

...