Enum variable default value?

前端 未结 1 1419
南旧
南旧 2020-12-13 23:39

The question is simple:

#include 

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

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


        
相关标签:
1条回答
  • 2020-12-14 00:17

    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

    0 讨论(0)
提交回复
热议问题