T
Troy Hanson
I use this kind of construct sometimes:
typedef enum color {
red,
orange,
blue
} color;
char *colors_strs[] = { "red", "orange", "blue" };
That way, I can easily print the textual name of enum variables, like:
color foreground = blue;
printf("foreground is %s", colors_strs[ foreground ] );
Maybe there's a more clever way to have my enum's associatiable with a
string (any ideas?) - if not, I'd at least like to automate the
generation of my enum and associated char *array[] using a macro. I'm
using GNU cpp.
I'm imagine its usage would look something like
ENUM_STRING( color, red, orange, blue );
that would produce the enum declaration and the color_strs[] above.
I've fiddled with cpp macros but to no avail. I haven't been able to
produce one that will stringify each arg in a vararg list. The closest
I could get, below, stringifies its entire vararg list (you get "red,
orange, blue" as a single string). I'd like to figure out how to get
"red", "orange", "blue".
#define ENUM_STRING( enm, ...) char * enm ## _str = #__VA_ARGS__;
typedef enum enm { __VA_ARGS__ } enm;
typedef enum color {
red,
orange,
blue
} color;
char *colors_strs[] = { "red", "orange", "blue" };
That way, I can easily print the textual name of enum variables, like:
color foreground = blue;
printf("foreground is %s", colors_strs[ foreground ] );
Maybe there's a more clever way to have my enum's associatiable with a
string (any ideas?) - if not, I'd at least like to automate the
generation of my enum and associated char *array[] using a macro. I'm
using GNU cpp.
I'm imagine its usage would look something like
ENUM_STRING( color, red, orange, blue );
that would produce the enum declaration and the color_strs[] above.
I've fiddled with cpp macros but to no avail. I haven't been able to
produce one that will stringify each arg in a vararg list. The closest
I could get, below, stringifies its entire vararg list (you get "red,
orange, blue" as a single string). I'd like to figure out how to get
"red", "orange", "blue".
#define ENUM_STRING( enm, ...) char * enm ## _str = #__VA_ARGS__;
typedef enum enm { __VA_ARGS__ } enm;