Back to results for “Enums”
C++ › Enums & Enum Classes

How do you convert between an enum class and its underlying integer?

Intermediate

Answer

Because enum class doesn't convert implicitly, you convert explicitly with static_cast: static_cast<int>(e) to get the value, and static_cast<Enum>(i) to build an enum from an integer. C++23 adds std::to_underlying for a clearer enum-to-integer conversion. Explicit conversion keeps the type safety while allowing needed interop.
enum class E : int { X = 5 };
int i = static_cast<int>(E::X);      // 5
E e = static_cast<E>(5);
// C++23: int j = std::to_underlying(E::X);
Real-world example Serializing an enum class to a file requires an explicit static_cast to its underlying int.

Common follow-ups: Why is the conversion explicit? | What does std::to_underlying do?