Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

c - Get enum value by name

I have an enumeration, which contains hundreds of entries.

I will be getting the value of the enumeration as a string. Is there any way to convert the string into an enum value? Otherwise, I will end up using hundreds of if statements.

Consider

enum Colors { Red, Green, Blue, Yellow ... } there are more than 100 entries

I will be getting "Red" in a string variable,

String color = "Red"; // "Red" would be generated dynamically.

Normally we access the enum in the following way, Colors::Red, Colors::Blue etc... is there any way in which we can access it in a way something like this:

Colors::color; // i.e enumtype::stringVariable

In many posts here, it’s given that we can use map, but again while constructing map we will end up in using hundreds of ifs.

Is there any way to avoid this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's a C way of doing it, similar to Paddy's C++ map. The macro guarantees that the name and corresponding enum are tied together.

enum Colors { NoColor, Red, Green, Blue, Yellow };

enum Colors get_color(const char *s)
{
    const struct {
        char *name;
        enum Colors color;
    } colormap[] = {
#define Color(x) {#x, x}
        Color(Red),
        Color(Green),
        Color(Blue),
        Color(Yellow)
#undef Color
    };
    for (size_t i = 0; i < sizeof colormap / sizeof colormap[0]; ++i) {
        if (!strcmp(s, colormap[i].name)) {
            return colormap[i].color;
        }
    }
    return NoColor;
}


EDIT As @sh1 suggested in a comment (which has now gone), you could use an X-macro to define the list of colors. This avoids defining the list twice. Here's the above example rewritten using an X-macro - thanks to sh1 for the hint:
#define COLORS  X(Red), X(Green), X(Blue), X(Yellow),

enum Colors {
    NoColor, 
#define X(x) x
    COLORS
#undef X
};

enum Colors get_color(const char *s)
{
    const struct {
        char *name;
        enum Colors color;
    } colormap[] = {
#define X(x) {#x, x}
        COLORS
#undef X
    };
...etc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...