Haspemulator Haspemulator - 1 year ago 125
C++ Question

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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download