C: Map string to ENUM [duplicate]

$ cat wd.c
#include <stdio.h>

#define mklist(f) \
    f(MONDAY) f(TUESDAY) f(WEDNESDAY)

#define f_enum(x) x,
#define f_arr(x) {x, #x},

enum weekdays { mklist(f_enum) WD_NUM };

struct { enum weekdays wd; char * str; } wdarr[] = { mklist(f_arr) };

int main(int argc, char* argv[]) {
    int i;
    for (i=0; i < sizeof(wdarr)/sizeof(wdarr[0]); i++) {
        if (strcmp(argv[1], wdarr[i].str) == 0) {
            printf("%d %s\n", wdarr[i].wd, wdarr[i].str);
            return 0;
        }
    }
    printf("not found\n");
    return 1;
}
$ make wd
cc     wd.c   -o wd
$ ./wd MONDAY
0 MONDAY
$ ./wd TUESDAY
1 TUESDAY
$ ./wd FOODAY
not found

is my favorite way to do such things. This ensures that no consistency errors can occur between the enum and the mapping array.

Leave a Comment