简体   繁体   中英

What are global strongly-typed enums initialized to by default in C++?

I'm trying to determine the default value to which global strongly-type enums are initialized. The following code of course does not compile.

#include <iostream>
using namespace std;

enum class A{a=10, b=20};

// Global strongly-typed enum, uninitialized
A k;

int main() {
    if(k==A::a)
        cout<<"Equal to a"<<endl;
    else if(k==A::b)
        cout<<"Equal to b"<<endl;
    else if(k==0)
        cout<<"Equal to zero"<<endl;

    return 0;
}

What is 'k' initialized to?

k has static storage duration and static objects are zero initialized, we can see this by going to the draft C++ standard section 3.6.2 Initialization of non-local variables paragraph 2 :

Variables with static storage duration (3.7.1) or thread storage duration (3.7.2) shall be zero-initialized (8.5) before any other initialization takes place. [...]

for scalar types that means initialization to zero, which is covered section 8.5 paragraph 6 which says:

To zero-initialize an object or reference of type T means:

and includes the following bullet:

if T is a scalar type (3.9), the object is initialized to the value obtained by converting the integer literal 0 (zero) to T;105

we know an enum is a scalar type from section 3.9 Types paragraph 9 which says:

Arithmetic types (3.9.1), enumeration types, pointer types, pointer to member types (3.9.2), std::nullptr_- t, and cv-qualified versions of these types (3.9.3) are collectively called scalar types.[...]

zero is a valid value since the underlying type can contain its value and section 7.2 Enumeration declarations paragraph 8 says that an enumeration can take a value not defined by its enumerators:

[...]It is possible to define an enumeration that has values not defined by any of its enumerators.[...]

It is zero initialized. Take into account that the underlaying type of this enumeration is int (by default) and 0 is a valid enumerator though it is not explicitly used in any enumerator definition of the enumeration..

Only you have to write

else if( k == static_cast<A>( 0 ) )
    cout<<"Equal to zero"<<endl;

If you would use C# then zero can be implicitly converted to an enumeration of any type.:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM