4

What is the default value of enum class variable without initialization? The following code prints weird result.

#include <iostream>
#include <cstdio>

using namespace std;

struct C {
    C() {
        m_a = 1;
    }

    enum class E:bool {
        a = false,
        b = true,
    };

    int m_a;
    E m_e;
};

int main()
{
    C c;
    cin >> c.m_a;
    printf("m_e: %d; compare to C::E::a: %d\n", static_cast<int>(c.m_e), c.m_e == C::E::a);
    return 0;
}

Build with gcc version 9.4.0 (Ubuntu 9.4.0-1ubuntu1~20.04.1)

g++ -g -o c c.cpp
# run, input 1 and get the result.
./c
1
m_e: 252; compare to C::E::a: 253
# run c, input 2 and get the result.
./c
2
m_e: 254; compare to C::E::a: 255

Q1: Why m_e is not initialized as C::E::a (value false == 0?) or C::E::b (value true == 1?)

Q2: Why dose the comparison expression c.m_e == C::E::a return 253/255, but not false (value 0) or true (value 1)?

0

1 Answer 1

5

What is the default value of enum class variable without initialization?

It's indeterminate since you never initialized it. Reading from c.m_e will therefore make your program have undefined behavior and the program could show just about any value - or no value and crash (or worse).

Change E m_e; to

E m_e{};

and it'll be zero initialized which will mean false in your case.

Note: Zero initializing an enum class may lead to confusing results if 0 isn't actually the value of one of the defined enumerators. It'll zero initialize the enum class's base type nevertheless.

Better be explicit:

E m_e{E::a};

Q1: Why m_e is not initialized as C::E::a (value false == 0?) or C::E::b (value true == 1?)

Because, it's not initialized and anything may show up - or not show up at all.

Q2: Why does the comparison expression c.m_e == C::E::a return 253/255, but not false (value 0) or true (value 1)?

Again. The behavior of the program is undefined.

Note: In the current MSVC, when you do cin >> c.m_a; and later print the value of c.m_e, it'll show the value you entered into c.m_a. Strange? No, that's just one way undefined behavior may show up.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the kind reply. Is there any C++ standard clause about enum class initialization?
@sfz You're welcome. I don't have the standard handy but you can read about default initialization @ cppreference. Search to highlight the word "indeterminate" on that page. It's not about enum classes specifically, but the same rules apply.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.