Retrieving Enum Values as Text in C
In C , the default behavior for printing enums is to output their numerical values. However, there are situations where it is desirable to retrieve the textual representation of an enum value.
Solutions Without if/switch:
Using a Map:
#include <map> #include <string_view> enum Errors { ErrorA = 0, ErrorB, ErrorC }; std::ostream& operator<<(std::ostream& out, const Errors value) { static const auto strings = []() { std::map<Errors, std::string_view> result; #define INSERT_ELEMENT(p) result.emplace(p, #p); INSERT_ELEMENT(ErrorA); INSERT_ELEMENT(ErrorB); INSERT_ELEMENT(ErrorC); #undef INSERT_ELEMENT return result; }(); return out << strings[value]; }
Using an Array with Linear Search:
#include <string_view> enum Errors { ErrorA = 0, ErrorB, ErrorC }; std::ostream& operator<<(std::ostream& out, const Errors value) { #define MAPENTRY(p) {p, #p} const struct MapEntry { Errors value; std::string_view str; } entries[] = { MAPENTRY(ErrorA), MAPENTRY(ErrorB), MAPENTRY(ErrorC), {ErrorA, 0} // Placeholder for default case }; #undef MAPENTRY const char* s = 0; for (const MapEntry* i = entries; i->str; i++) { if (i->value == value) { s = i->str; break; } } return out << s; }
Using a Switch/Case Statement:
#include <string> enum Errors { ErrorA = 0, ErrorB, ErrorC }; std::ostream& operator<<(std::ostream& out, const Errors value) { return out << [value]() { #define PROCESS_VAL(p) case(p): return #p; switch (value) { PROCESS_VAL(ErrorA); PROCESS_VAL(ErrorB); PROCESS_VAL(ErrorC); } #undef PROCESS_VAL }(); }
Test Case:
#include <iostream> int main() { std::cout << ErrorA << std::endl << ErrorB << std::endl << ErrorC; return 0; }
The above is the detailed content of How to Retrieve Enum Values as Text in C ?. For more information, please follow other related articles on the PHP Chinese website!