How to Retrieve Enum Values as Text in C ?
Nov 30, 2024 am 07:56 AMRetrieving 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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

What are the types of values returned by c language functions? What determines the return value?

C language function format letter case conversion steps

What are the definitions and calling rules of c language functions and what are the

Where is the return value of the c language function stored in memory?

How does the C Standard Template Library (STL) work?

How do I use algorithms from the STL (sort, find, transform, etc.) efficiently?
