C++20 has no built-in way to get an enumerator's name, so write one function: a switch that returns std::string_view, as in case Color::Red: return "Red";, with a fallback return "unknown"; after it. Add an operator<< and a std::formatter<Color> so std::cout and std::format print the name. For the number, use static_cast<int>(c).
An enum is a set of named integers, and the names are gone once the program compiles: std::cout prints an old-style enum as a number and refuses an enum class outright. Every answer therefore writes the names down somewhere, and the choices differ in where: a switch, an array, a table of value and name pairs, a macro list, or the compiler's own spelling of a template argument. The sections below cover the switch, printing with << and std::format, iterating over an enum, turning a string back into an enum, the X-macro and the compiler trick behind magic_enum, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1A switch that returns std::string_viewRecommended
The plain answer is the right one for most enums: a constexpr function with one case per enumerator. Return std::string_view: the names are string literals, which live for the whole program, so the view never dangles and nothing is allocated. Leave out default: and put the fallback after the switch instead; with -Wall, GCC and Clang then warn about every enumerator you forgot to handle, which a default would silence. An operator<< that calls the function makes std::cout print names too.
#include <iostream> #include <string> #include <string_view> enum class Color { Red, Green, Blue }; enum Status { Ok, Failed }; // old unscoped enum, for comparison // One switch, one place to add a name. Returning string_view costs // nothing: the names are string literals that live for the whole program. constexpr std::string_view to_string(Color c) { switch (c) { case Color::Red: return "Red"; case Color::Green: return "Green"; case Color::Blue: return "Blue"; } return "unknown"; // a value outside the list, e.g. Color(7) } // Lets std::cout << Color::Green print the name. std::ostream& operator<<(std::ostream& os, Color c) { return os << to_string(c); } int main() { Color c = Color::Green; std::cout << to_string(c) << '\n'; std::cout << "via <<: " << Color::Blue << '\n'; // Need a std::string? Construct one from the view. std::string label = "color=" + std::string(to_string(Color::Red)); std::cout << label << '\n'; // An enum class converts to its number only when you ask. std::cout << "number: " << static_cast<int>(c) << '\n'; // An unscoped enum converts silently, so << prints its number. std::cout << "Status: " << Failed << '\n'; // Any int fits in the enum's underlying type, so guard the default. std::cout << "cast 7: " << static_cast<Color>(7) << '\n'; // constexpr: the lookup can even run at compile time. static_assert(to_string(Color::Blue) == "Blue"); }
Output
The function prints Green, and through the operator via <<: Blue. To join the name to other text, build a std::string from the view first: color=Red. The two casts show the difference between the enum kinds: an enum class gives its number only through static_cast<int> (number: 1), while the unscoped Status converts on its own, so << printed Status: 1 with no operator at all. static_cast<Color>(7) compiles and is a valid value, since any int fits an enum class, which is why the fallback exists: it printed cast 7: unknown. Without that last return, the function would run off its end, which is undefined behaviour. The static_assert shows the lookup also works at compile time. C++23 adds std::to_underlying(c) for the cast; this page compiles as C++20.
2Printing with std::format: a std::formatter specialization
operator<< does not teach std::format anything: std::format("{}", level) fails to compile until the enum has a std::formatter. The shortest correct one derives from std::formatter<std::string_view>, which already parses width, fill and alignment, and passes it the name. Specializing std::formatter for your own type is allowed; for a standard library type, it is not.
#include <format> #include <iostream> #include <string> #include <string_view> enum class Level { Debug, Info, Warning, Error }; constexpr std::string_view to_string(Level l) { switch (l) { case Level::Debug: return "debug"; case Level::Info: return "info"; case Level::Warning: return "warning"; case Level::Error: return "error"; } return "unknown"; } // Inherit the string_view formatter: it parses width, fill and // alignment for us, and we only swap the enum for its name. template <> struct std::formatter<Level> : std::formatter<std::string_view> { auto format(Level l, std::format_context& ctx) const { return std::formatter<std::string_view>::format(to_string(l), ctx); } }; int main() { std::cout << std::format("level={}", Level::Warning) << '\n'; // Format specs work as they do for strings. std::cout << std::format("[{:>8}]", Level::Info) << '\n'; std::cout << std::format("[{:*^9}]", Level::Error) << '\n'; // The number is still one cast away. Level l = Level::Error; std::cout << std::format("{} = {}", l, static_cast<int>(l)) << '\n'; }
Output
level=warning comes from the plain {}, and the format specs work as they do for any string: {:>8} gave [ info] and {:*^9} gave [**error**]. The number still needs its cast: error = 3. For more on format specs, see formatting a string.
3Iterating over an enum
C++ cannot loop over an enum's values directly, and the language does not even say how many there are. When the values run 0 to N - 1, the usual fix is a Count enumerator at the end: it equals the number of real values, sizes a names array, and bounds an int loop that casts each step. When the values have gaps, such as HTTP status codes, counting through them would visit numbers that are not in the enum, so list the values instead, paired with their names.
#include <array> #include <cstddef> #include <iostream> #include <string_view> #include <utility> // Contiguous values 0..N-1 with a Count sentinel at the end. enum class Suit { Clubs, Diamonds, Hearts, Spades, Count }; // The names, in the same order as the enum. static_assert fails the // build if someone adds a suit and forgets its name. constexpr std::array<std::string_view, 4> suit_names = { "Clubs", "Diamonds", "Hearts", "Spades"}; static_assert(suit_names.size() == static_cast<std::size_t>(Suit::Count)); constexpr std::string_view to_string(Suit s) { auto i = static_cast<std::size_t>(s); return i < suit_names.size() ? suit_names[i] : "unknown"; } // Values with gaps cannot be counted through or used as an index, // so pair each value with its name in one table. enum class Http { Ok = 200, NotFound = 404, ServerError = 500 }; constexpr std::array<std::pair<Http, std::string_view>, 3> http_names = {{ {Http::Ok, "Ok"}, {Http::NotFound, "NotFound"}, {Http::ServerError, "ServerError"}, }}; constexpr std::string_view to_string(Http h) { for (auto [value, name] : http_names) { if (value == h) return name; } return "unknown"; } int main() { // 1. Count through the contiguous enum with an int, cast each step. for (int i = 0; i < static_cast<int>(Suit::Count); ++i) { auto s = static_cast<Suit>(i); std::cout << i << ' ' << to_string(s) << '\n'; } // 2. Loop over the table: works for any enum, gaps or not. for (auto [value, name] : http_names) { std::cout << static_cast<int>(value) << ' ' << name << '\n'; } std::cout << to_string(Http::NotFound) << '\n'; }
Output
The int loop prints 0 Clubs to 3 Spades, and the table loop prints 200 Ok, 404 NotFound and 500 ServerError. The static_assert ties the names array to Count, so adding a suit without a name stops the build; it does not catch two names swapped. Count has a cost: it is a value of the enum, so a switch must handle it and it shows up wherever every enumerator is listed. A for (auto s = Suit::Clubs; …; ++s) loop needs an operator++ you write yourself, because an enum class has none.
4Converting a string back to an enum
The reverse direction comes up as soon as names arrive from a config file or a command line. Keep one table of value and name pairs and drive both functions from it, so they cannot drift apart. The lookup can fail, so return std::optional<Fruit>: the caller has to check, and no fake "default" value sneaks through.
#include <array> #include <iostream> #include <optional> #include <string_view> #include <utility> enum class Fruit { Apple, Banana, Cherry }; // One table drives both directions, so they cannot disagree. constexpr std::array<std::pair<Fruit, std::string_view>, 3> fruit_names = {{ {Fruit::Apple, "apple"}, {Fruit::Banana, "banana"}, {Fruit::Cherry, "cherry"}, }}; constexpr std::string_view to_string(Fruit f) { for (auto [value, name] : fruit_names) { if (value == f) return name; } return "unknown"; } // "No such name" is an ordinary outcome, so return an empty optional // instead of throwing or inventing a default value. constexpr std::optional<Fruit> fruit_from_string(std::string_view text) { for (auto [value, name] : fruit_names) { if (name == text) return value; } return std::nullopt; } int main() { for (std::string_view input : {"banana", "cherry", "Cherry", "kiwi"}) { if (auto f = fruit_from_string(input)) { std::cout << input << " -> Fruit " << static_cast<int>(*f) << " (" << to_string(*f) << ")\n"; } else { std::cout << input << " -> not a fruit\n"; } } // Round trip: every value survives name -> value -> name. bool ok = true; for (const auto& entry : fruit_names) { Fruit f = entry.first; ok = ok && fruit_from_string(to_string(f)) == f; } std::cout << "round trip ok: " << std::boolalpha << ok << '\n'; }
Output
banana -> Fruit 1 (banana) found the value, and kiwi -> not a fruit came back empty. So did Cherry -> not a fruit: the comparison is exact. To accept any case, compare both strings in lower case (see converting a string to lowercase). The loop at the end checks every entry, printing round trip ok: true, which makes a cheap unit test for the table. A linear search is fine for a few dozen names; for hundreds, build a std::unordered_map once.
5One list for the enum and its names: the X-macro
Every approach so far writes each name twice, once in the enum and once in the lookup. An X-macro writes it once: a macro holds the list, and each use defines X to expand every entry differently, as an enumerator, as a string with the # operator, or as a value. It is old-fashioned preprocessor code, but it is standard, and for long lists that change often it is the safest of the hand-written options.
#include <array> #include <cstddef> #include <iostream> #include <string_view> // The list lives in exactly one place. Each use below defines X to // pick what it needs from every entry. #define PLANET_LIST(X) \ X(Mercury) \ X(Venus) \ X(Earth) \ X(Mars) enum class Planet { #define X(name) name, PLANET_LIST(X) #undef X }; // #name turns the token into a string literal: Mercury -> "Mercury". constexpr std::array planet_names = { #define X(name) std::string_view(#name), PLANET_LIST(X) #undef X }; constexpr std::array all_planets = { #define X(name) Planet::name, PLANET_LIST(X) #undef X }; constexpr std::string_view to_string(Planet p) { return planet_names[static_cast<std::size_t>(p)]; } int main() { std::cout << to_string(Planet::Earth) << '\n'; // Add X(Jupiter) to the list and the enum and both arrays grow. std::cout << planet_names.size() << " planets:"; for (Planet p : all_planets) { std::cout << ' ' << to_string(p); } std::cout << '\n'; }
Output
to_string(Planet::Earth) prints Earth, and the list gives 4 planets: Mercury Venus Earth Mars. Indexing planet_names by the value is safe here because the macro numbers the enumerators from 0 in list order; an entry such as X(name, 404) with explicit values needs the pair table from section 3 instead. The cost is readability: an IDE can't always show what PLANET_LIST expands to, and the name is exactly the identifier, so "Not found" with a space needs a second macro argument.
6Letting the compiler name it: __PRETTY_FUNCTION__ and magic_enum
The top answers on the subject point to magic_enum, a header-only library that needs no list at all. Its trick: in a function template template <auto V>, GCC and Clang put the template argument, spelled as source code, into __PRETTY_FUNCTION__, so instantiating it for each number from 0 to N - 1 and reading the text back yields every name. The minimal version below shows how it works; it is compiler-specific, not standard C++.
#include <array> #include <cstddef> #include <iostream> #include <string_view> #include <utility> // GCC and Clang spell the template argument out in __PRETTY_FUNCTION__, // e.g. "... [with auto V = Color::Green; ...]". Not standard C++: // this is the trick the magic_enum library builds on. template <auto V> constexpr std::string_view enum_name() { std::string_view f = __PRETTY_FUNCTION__; auto start = f.find("V = ") + 4; auto end = f.find_first_of(";]", start); std::string_view name = f.substr(start, end - start); if (name.starts_with('(')) return {}; // "(Color)5": no such enumerator return name.substr(name.rfind(':') + 1); // drop "Color::" } enum class Color { Red, Green, Blue }; // Ask the compiler for the names of 0..N-1 once, at compile time. template <typename E, std::size_t N = 16, std::size_t... I> constexpr auto names_table(std::index_sequence<I...>) { return std::array<std::string_view, N>{enum_name<static_cast<E>(I)>()...}; } template <typename E, std::size_t N = 16> constexpr std::string_view to_string(E e) { constexpr auto table = names_table<E, N>(std::make_index_sequence<N>{}); auto i = static_cast<std::size_t>(e); return i < N && !table[i].empty() ? table[i] : "unknown"; } int main() { std::cout << enum_name<Color::Green>() << '\n'; // The value can come from a variable: the table was built for 0..15. for (int i = 0; i < 4; ++i) { std::cout << i << ' ' << to_string(static_cast<Color>(i)) << '\n'; } }
Output
enum_name<Color::Green>() prints Green, and the table built for 0 to 15 names a runtime value: 0 Red, 1 Green, 2 Blue, and 3 unknown because GCC spells a value with no enumerator as a cast, such as (Color)5, which enum_name turns into an empty name. The limits come with the trick: only values in the scanned range get names (magic_enum scans -128 to 127 by default, so HTTP codes or bit flags need settings), each scanned value instantiates a template, which slows compilation, and the parsing depends on the compiler's wording. For a project that can take the dependency, magic_enum handles these cases and MSVC. C++26 adds static reflection, which lists an enum's enumerators and their names in standard code; this page compiles as C++20.
7Which should you use?
| Method | Names written | Values with gaps | Best for |
|---|---|---|---|
| switch returning string_view | Twice, -Wall warns on a miss | Yes | Most enums |
| std::formatter<E> + operator<< | Reuses to_string | Yes | Printing with format and cout |
| names array + Count | Twice, order must match | No | Contiguous enums you loop over |
| array of {value, name} pairs | Twice, side by side | Yes | Both directions, iteration, parsing |
| X-macro | Once | Needs a second column | Long lists that change often |
| __PRETTY_FUNCTION__ / magic_enum | Never | Only inside the scanned range | Projects that accept a compiler trick or library |
Frequently asked questions
Is there a built-in way to get an enum name as a string in C++?
Not in C++20 or C++23: the names exist only in the source code, so you write them down yourself with a switch, a table or an X-macro, or use a library such as magic_enum, which reads them from __PRETTY_FUNCTION__. C++26 adds static reflection, which can list an enum's enumerators and their names in standard code once compilers ship it.
Why does std::cout << of my enum class not compile?
An enum class does not convert to int on its own, so no operator<< matches. Either cast it, std::cout << static_cast<int>(c), which prints the number, or write std::ostream& operator<<(std::ostream& os, Color c) that prints the name. An old unscoped enum does convert, which is why it prints a number instead of failing.
How do I get the number of values in an enum?
There is no standard size for an enum. Add a last enumerator such as Count to an enum whose values start at 0 and have no gaps: static_cast<int>(Suit::Count) is then the number of real values. For enums with gaps, keep a constexpr std::array of all values and use its size(). magic_enum::enum_count<E>() does it for you if you use the library.
How do I convert an int to an enum class in C++?
Use static_cast<Color>(n). It compiles for any int and does no check, so a value such as 7 becomes a Color with no name. Check the range first (n >= 0 && n < static_cast<int>(Color::Count)) or give your to_string a fallback such as "unknown". The other direction is static_cast<int>(c), or std::to_underlying(c) in C++23.
Should to_string return std::string, const char* or std::string_view?
Return std::string_view (or const char*) when the names are string literals: they live for the whole program, so nothing is copied or allocated and the function can be constexpr. Convert at the call site with std::string(to_string(c)) when you need a std::string. Return std::string only if you build the name at run time, for example from several parts.
Should the switch have a default case?
Usually not. Without default:, compiling with -Wall (which turns on -Wswitch) warns about every enumerator the switch does not handle, so adding a value to the enum points you at each switch to update. Put the fallback return "unknown"; after the switch instead: it handles values made by a cast, and it keeps the function from running off its end, which is undefined behaviour.