Home >Backend Development >C++ >How Can I Print C Enum Values as Text Without Using if/switch Statements?
Printing Enum Values as Text without if/switch in C
In C , enumerations provide a way to assign integer values to symbolic names. However, when printing an enum value to the console, it typically outputs the associated integer instead of the symbolic name.
To overcome this limitation and print enum values as text, let's explore three efficient solutions:
1. Using a Map:
Utilizing a std::map allows for efficient lookup of enum values to their corresponding text representations.
#include <map> #include <string_view> enum Errors { ErrorA = 0, ErrorB, ErrorC }; // Custom insertion function for map #define INSERT_ELEMENT(p) result.emplace(p, #p); // Initialize the map static const auto strings = []() { std::map<Errors, std::string_view> result; INSERT_ELEMENT(ErrorA); INSERT_ELEMENT(ErrorB); INSERT_ELEMENT(ErrorC); return result; }; std::ostream& operator<<(std::ostream& out, const Errors value) { return out << strings[value]; }
2. Using an Array of Structures with Linear Search:
This approach involves creating an array of structures, each containing an enum value and its corresponding text. Linear search is then used to retrieve the text for the desired enum value.
#include <string_view> enum Errors { ErrorA = 0, ErrorB, ErrorC }; // Structure for mapping enum to text struct MapEntry { Errors value; std::string_view str; }; std::ostream& operator<<(std::ostream& out, const Errors value) { const MapEntry entries[] = { {ErrorA, "ErrorA"}, {ErrorB, "ErrorB"}, {ErrorC, "ErrorC"} }; const char* s = nullptr; for (const MapEntry* i = entries; i->str; i++) { if (i->value == value) { s = i->str; break; } } return out << s; }
3. Using switch/case:
While less efficient than the map approach, switch/case can also be used to map enum values to text.
#include <string> enum Errors { ErrorA = 0, ErrorB, ErrorC }; std::ostream& operator<<(std::ostream& out, const Errors value) { return out << [value]() { switch (value) { case ErrorA: return "ErrorA"; case ErrorB: return "ErrorB"; case ErrorC: return "ErrorC"; } }; }
The above is the detailed content of How Can I Print C Enum Values as Text Without Using if/switch Statements?. For more information, please follow other related articles on the PHP Chinese website!