2
  • compiler : clang++
  • c++ standard : c++20

I tried to run the code, and the results met my expectations very well.

#include <iostream>

using namespace std;

int main()
{
    enum class Num : int
    {
        one = 1,
        two = 2,
        zero = 0
    };

    Num e = Num::one;
    auto a = static_cast<std::underlying_type_t<Num>>(e);

    cout << "-----------" << endl;
    cout << a << endl;
    cout << "-----------" << endl;
    return 0;
}

result:

-----------
1
-----------

But when I made a small modification, changing the underlying type of enum class from int to int8_t,the result was unexpected.

#include <iostream>

using namespace std;

int main()
{
    enum class Num : int8_t // from 'int' to 'int8_t'
    {
        one = 1,
        two = 2,
        zero = 0
    };

    Num e = Num::one;
    auto a = static_cast<std::underlying_type_t<Num>>(e);

    cout << "-----------" << endl;
    cout << a << endl;
    cout << "-----------" << endl;
    return 0;
}

result:

-----------

-----------

What happened here?

nullptr
  • 321
  • 1
  • 9

1 Answers1

3

int8_t maps to char, and this type is by default printed as its character representation. The character with value 1 is a control character which you can't see.

So, cout << (int8_t)65 will print A and not 65 because the single character 'A' has value 65.

You can avoid that by casting to int before printing: cout << (int)a, or alternatively use the unary plus operator: cout << +a.

CherryDT
  • 25,571
  • 5
  • 49
  • 74