Skip to content
Tutorials Center
My learning

Topics

Lesson 83 of 171 ยท Object-Oriented Programming

Enumerations: enum and enum class

Learn C++ enumerations - unscoped enum vs scoped enum class, underlying types, std::to_underlying, enums in switch, converting to strings, and type-safe enum flags.

Plenty of values in a program come from a small, fixed set: the days of the week, the state of a network connection, the suit of a playing card, the log level of a message. You could store them as plain integers (0 for Monday, 1 for Tuesday, ...), but then nothing stops someone from passing 42 as a day, and every reader has to remember what 3 means. An enumeration gives each value a name and gives the whole set its own type, so the compiler can check how it's used.

C++ has two kinds. The original unscoped enum, inherited from C, is convenient but leaky: its names spill into the surrounding scope and it converts silently to int. The modern scoped enum class (C++11) fixes both problems and is what you should use by default. This lesson covers both, plus underlying types, converting to and from integers (including C++23's std::to_underlying), using enums in switch, turning them into text, and building type-safe bit flags.

Unscoped enums

An enum declaration lists named constants called enumerators. Unless you say otherwise, the first is 0 and each following one is one more than the previous. You can assign any value explicitly, and later enumerators continue counting from there.

C++ Unscoped enums and their quirks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Created is 201 because it follows Ok = 200. Notice how loose the rules are: Wednesday is visible without qualification, an enumerator turns into an int whenever needed, and two completely unrelated enumerations can be compared. The standard allows that comparison (C++20 deprecated it); GCC compiles it and only prints the -Wenum-compare warning you see above the output. The only direction C++ blocks is int โ†’ enum, which needs a cast.

Leaking names is the bigger practical problem. Two unscoped enums in the same scope can't both have a None or an Error enumerator, which is why old C and C++ code is full of prefixes like COLOR_RED and LOG_ERROR.

Scoped enums: enum class

Write enum class (or the equivalent enum struct) and you get a scoped enumeration:

  • Enumerators live inside the enum's scope: you write Suit::Hearts, so different enums can reuse the same names.
  • There is no implicit conversion to int or anything else. Arithmetic and comparisons with integers don't compile.
  • Enumerators of the same enum can still be compared with each other (==, <, ...), using their underlying values.
C++ Scoped enums are type-safe

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Every commented line is a mistake the compiler now catches. When you really need the number, you say so with a cast, which makes the conversion visible in the code.

using enum (C++20)

Writing Suit:: over and over can get noisy, particularly inside a switch. C++20's using enum brings all enumerators of a scoped enum into the current scope, but only where you ask for it:

C++
std::string_view symbol(Suit suit) {
    using enum Suit;                 // Clubs, Diamonds, ... are visible inside this function
    switch (suit) {
    case Clubs:    return "โ™ฃ";
    case Diamonds: return "โ™ฆ";
    case Hearts:   return "โ™ฅ";
    case Spades:   return "โ™ ";
    }
    return "?";
}

Underlying types

Every enumeration is stored as some integer type, its underlying type. For a scoped enum it is int unless you specify another; for an unscoped enum without one, the compiler picks an integer type big enough for all the values. You can choose it explicitly after a colon, which is useful to save space in large arrays or to match a file format or protocol:

C++ Choosing the underlying type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

std::underlying_type_t<E> from <type_traits> names the underlying type, which is handy in generic code. A fixed underlying type also allows a forward declaration: enum class Suit : std::uint8_t; in a header lets other code use Suit parameters without seeing the enumerator list (scoped enums can always be forward-declared, since they default to int).

Converting between enums and integers

From enum to integer, C++23 adds std::to_underlying(e) (in <utility>). It converts to exactly the underlying type, so you can't accidentally pick the wrong integer type. Before C++23, write static_cast<std::underlying_type_t<E>>(e), or just static_cast<int>(e) when you know it fits.

From integer to enum you need static_cast<E>(n), and that's where care is needed: the cast doesn't check anything. For an enum with a fixed underlying type, any value of that type is technically valid (static_cast<Suit>(17) is a Suit that matches no enumerator). For an unscoped enum without a fixed type, casting a value outside its range is undefined behavior. Either way, when the number comes from outside (a file, the network, the user), validate it before you trust it:

C++ Validating numbers before converting to an enum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The range check works because the enumerators are consecutive. For enums with gaps (like HttpStatus above), check against the list of valid values with a switch instead. The last line shows why name needs its final return: a Priority can hold 9, which matches no case.

Enums in switch statements

Enums and switch belong together (see switch Statements). The compiler knows the full list of enumerators, so it can tell you when you forget one: with -Wall, GCC's -Wswitch warns "enumeration value 'Critical' not handled in switch". That warning is only possible when the switch has no default: label, because a default handles everything, including new enumerators added years later.

That gives a simple, powerful habit:

  • In a switch over an enum, list every enumerator and don't write default.
  • Handle the "impossible" out-of-range value after the switch, as name does above with its final return.

When someone adds Priority::Blocker, every such switch in the program produces a warning pointing to the code that must be updated. With default:, the new value would be silently treated as whatever the default does. (Without the final return, GCC would also warn "control reaches end of non-void function", because it can't assume the enum holds a named value.)

Turning enums into text

C++ has no built-in way to get an enumerator's name as a string (static reflection, planned for C++26, will finally allow it). The common approaches are a switch like name above, or an array indexed by the underlying value for consecutive enums. To make an enum work directly with std::print and std::format, specialize std::formatter:

C++ Printing enums with a custom formatter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Because the formatter inherits from std::formatter<std::string_view>, width and alignment specs like {:<7} work for free. Custom formatters are explained more fully in Formatting with std::format and std::print.

Enum flags

Some settings are a set of options rather than one choice: a file can be readable and writable and executable. The classic C technique gives each option its own bit and combines them with | (see Bitwise Operators). With an unscoped enum this "just works" because enumerators convert to int, but the result of Read | Write is an int, so all type safety is gone.

With enum class you define the few operators you need yourself, and keep the type:

C++ Type-safe bit flags with enum class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The operators are constexpr, so flag combinations can be computed at compile time and checked with static_assert. has tests whether all bits of flag are set, which also works for combined flags. Many codebases wrap these few operators in a small macro or template so every flag enum gets them with one line. For a fixed number of anonymous bits without names, std::bitset is an alternative (see std::bitset).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. enum Level { Low, Mid = 5, High }; What is the value of High?

    An enumerator without an explicit value is one more than the previous one, so High follows Mid = 5 and is 6.
  2. 2. enum class Color { Red, Green }; int n = Color::Green; What happens?

    Scoped enumerations have no implicit conversion to integers. Write static_cast<int>(Color::Green) or std::to_underlying(Color::Green).
  3. 3. What does std::to_underlying(e) (C++23) return for enum class Code : std::uint8_t?

    std::to_underlying converts an enumeration value to exactly its underlying type, here std::uint8_t.
  4. 4. Why is it recommended to omit default: in a switch that lists every enumerator?

    -Wswitch only reports unhandled enumerators when there is no default label. Handle impossible values after the switch instead.
  5. 5. enum class Priority { Low, Normal, High }; What is static_cast<Priority>(7)?

    The cast performs no check. A scoped enum's underlying type is int, so 7 is representable, but it matches no enumerator, which is why external numbers must be validated before casting.

Summary

  • An enumeration is a distinct type with named constants. Values start at 0 and count up unless you assign them.
  • Unscoped enum leaks its names into the enclosing scope and converts implicitly to integers. enum class keeps names scoped (Suit::Hearts) and allows no implicit conversions. Prefer enum class.
  • using enum E; (C++20) brings a scoped enum's names into a local scope, convenient inside a switch.
  • The underlying type is int for scoped enums by default; choose another with enum class E : std::uint8_t. std::underlying_type_t<E> names it.
  • Convert to integers with std::to_underlying (C++23) or static_cast; convert from integers with static_cast only after validating the value.
  • Switch over enums without default: so -Wswitch flags missing cases, and handle out-of-range values after the switch.
  • There's no built-in enum-to-string; use a switch and a std::formatter specialization. Build type-safe flags by defining |, & and |= for an enum class.

Next: Nested and Local Classes, classes defined inside other classes and functions.