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?
If we do not explicitly assign values to enum names, the compiler by default assigns values starting from 0. For example, in the following C program, sunday gets value 0, monday gets 1, and so on.
The default value of an enumeration type E is the value produced by expression (E)0 , even if zero doesn't have the corresponding enum member.
The default value of an uninitialized enumeration, just like other value types, is zero.
The strongly-typed enumerations have to follow stronger rules: The enumerators can only be accessed in the scope of the enumeration. The enumerators don't implicitly convert to int. The enumerators aren't imported in the enclosing scope. The type of the enumerators is by default int.
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.[...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With