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

Popular posts from this blog

IF statement in MySQL trigger -

c++ - What does MSC in "// appease MSC" comments mean? -

javascript - Blogger related post gadget image Resize s72-c [ Need Expert Help ] -