Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get enum value by name

Tags:

c

enums

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?

like image 237
Gokul Kulkarni Avatar asked Aug 06 '13 02:08

Gokul Kulkarni


1 Answers

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
like image 138
William Morris Avatar answered Oct 01 '22 00:10

William Morris