Home > Backend Development > C++ > How Can I Easily Convert C Enums to Strings, Handling Typedefs and Unnamed Enums?

How Can I Easily Convert C Enums to Strings, Handling Typedefs and Unnamed Enums?

Patricia Arquette
Release: 2024-12-15 21:05:32
Original
963 people have browsed it

How Can I Easily Convert C   Enums to Strings, Handling Typedefs and Unnamed Enums?

Hassle-Free C Enum Conversion to Strings

Suppose you encounter named enums in your C code:

enum MyEnum {
      FOO,
      BAR = 0x50
};
Copy after login

And you seek a script to generate a header featuring a conversion function for each enum:

char* enum_to_string(MyEnum t);
Copy after login

With a straightforward implementation like this:

char* enum_to_string(MyEnum t){
      switch(t){
         case FOO:
            return "FOO";
         case BAR:
            return "BAR";
         default:
            return "INVALID ENUM";
      }
 }
Copy after login

However, things get tricky with typedefed enums and unnamed C enums. Let's delve into the best solutions:

X-Macros: The Champion

X-macros emerge as the top choice, offering an elegant solution:

#include <iostream>

enum Colours {
#   define X(a) a,
#   include "colours.def"
#   undef X
    ColoursCount
};

char const* const colours_str[] = {
#   define X(a) #a,
#   include "colours.def"
#   undef X
    0
};

std::ostream&amp; operator<<(std::ostream&amp; os, enum Colours c)
{
    if (c >= ColoursCount || c < 0) return os << "???";
    return os << colours_str[c];
}

int main()
{
    std::cout << Red << Blue << Green << Cyan << Yellow << Magenta << std::endl;
}
Copy after login

The accompanying file "colours.def" holds:

X(Red)
X(Green)
X(Blue)
X(Cyan)
X(Yellow)
X(Magenta)
Copy after login

Customizing String Output

For added flexibility, you can tweak the string output:

#define X(a, b) a,
#define X(a, b) b,

X(Red, "red")
X(Green, "green")
// etc.
Copy after login

The above is the detailed content of How Can I Easily Convert C Enums to Strings, Handling Typedefs and Unnamed Enums?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template