Enum variable default value?

C++VariablesEnumsDefault Value

C++ Problem Overview


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.

C++ Solutions


Solution 1 - C++

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHaspemulatorView Question on Stackoverflow
Solution 1 - C++Armen TsirunyanView Answer on Stackoverflow