Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 913
johngreen Avatar asked Aug 27 '14 13:08

johngreen


People also ask

What is the default value of enum in C?

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.

What is the default type of enum?

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.

What is the default value for an enum?

The default value of an uninitialized enumeration, just like other value types, is zero.

What is a strongly typed enum?

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.


1 Answers

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.[...]

like image 150
Shafik Yaghmour Avatar answered Oct 18 '22 19:10

Shafik Yaghmour