1

I want to convert a string to enum number. below code is what I want to do.

#define SELECT_DAY(s) s

enum sched {MON, TUE, WED};
int main(void)
{
    char *str = "TUE";

    printf("%d\n", SELECT_DAY(str));
    return 0;
}

Just you can see, str has "TUE" string's pointer. So, I thought that printf function will print out number 1. But, It printed out string's address.

printf("%d\n", TUE);

above code is what I expected. Can't the predecessor handle this operation ? I know that the way to convert a string to enum in C# can be possible. In C, is there no way to convert a string to enum number ?

knolz
  • 181
  • 4
  • 10
  • Possible duplicate of [C: Map string to ENUM](http://stackoverflow.com/questions/8642970/c-map-string-to-enum) – m.s. Nov 29 '15 at 13:21
  • What is "predecessor"? By the way, the preprocessor won't do such conversion because this isn't its task, and the processor (CPU) won't do such conversion because the symbol used in enum won't appear in executable bynary except as debug symbols. – MikeCAT Nov 29 '15 at 13:23
  • Possible duplicate of [Easy way to use variables of enum types as string in C?](http://stackoverflow.com/questions/147267/easy-way-to-use-variables-of-enum-types-as-string-in-c) – MikeCAT Nov 29 '15 at 13:24

1 Answers1

1

Well, in the C world, this is DIY.

There is not 'evident' way to do this, usually people use something like:

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

enum sched {MON, TUE, WED};

static const struct {
    enum sched val;
    const char *const str;
} enum_2_string_map[] = {
    { MON, "MON" },
    { TUE, "TUE" },
    { WED, "WED" }
};

enum sched string2enum(const char *str)
{
    int i;
    for (i = 0; i < sizeof(enum_2_string_map) / sizeof(*enum_2_string_map); i++) {
        if (strcmp(str, enum_2_string_map[i].str) == 0) {
            return enum_2_string_map[i].val;
        }
    }
    /* you need to decide what to do if string is not found; assert or return a
     * default value... you choose */
    abort();
}

#define SELECT_DAY(s) string2enum(s)

int main(void)
{
    char *str = "TUE";

    printf("%d\n", SELECT_DAY(str));
    return 0;
}

You will probably see implementations with macros to prevent to repeat the { MON, "MON" } (for example) or other that are not case sensitive, but more or less always the same way.

Some also create an array of string that they index with the enum value, but I dislike this way to do (enum are not always contiguous)

OznOg
  • 4,440
  • 2
  • 26
  • 35