How to convert enum names to string in c -
is there possibility convert enumerator names string in c?
another way, making preprocessor work. ensures enums , strings in sync.
#define foreach_fruit(fruit) \ fruit(apple) \ fruit(orange) \ fruit(grape) \ fruit(banana) \ #define generate_enum(enum) enum, #define generate_string(string) #string, enum fruit_enum { foreach_fruit(generate_enum) }; static const char *fruit_string[] = { foreach_fruit(generate_string) }; after preprocessor gets done, you'll have:
enum fruit_enum { apple, orange, grape, banana, }; static const char *fruit_string[] = { "apple", "orange", "grape", "banana", }; then like:
printf("enum apple string: %s\n",fruit_string[apple]); another way, if use case literally printing enum name:
#define str(x) #x then do:
printf("enum apple string: %s\n", str(apple));
Comments
Post a Comment