#include
#define ENUM_BODY(name, value) \
name = value,
#define AS_STRING_CASE(name, value) \
case name: return #name;
#define FROM_STRING_CASE(name, value) \
if (strcmp(str, #name) == 0) { \
return name; \
}
#define DEFINE_ENUM(name, list) \
typedef enum { \
list(ENUM_BODY) \
}name; \
const char* asString(name n) { \
switch (n) { \
list(AS_STRING_CASE) \
default: return ""; \
} \
} \
name fromString(const char* str) { \
list(FROM_STRING_CASE) \
return 0; /* assert? throw? */ \
}
#define ENUM_LIST(_) \
_(RED, 0) \
_(GREEN, 1) \
_(BLUE, 87)
DEFINE_ENUM(Color, ENUM_LIST)
int main() {
Color c = GREEN;
printf("%d\n",c);
printf("%s\n", asString(c));
printf("%d\n", fromString("BLUE"));
}
Another enum -> string can be found here