String representation of enumeration values

gcc 4.4.2 c89

I have the following listing:

enum drop_options_e { drop_ssm, drop_snm, drop_ssb }; 

I'm just wondering what is the best way to get the value of a string representation from an enumeration.

So, instead of returning a value of 0 for drop_ssm, I could get "drop_ssm" instead.

Thanks so much for any advice,

+4
source share
7 answers

One of the methods:

 enum drop_options_e { drop_ssm = 0, drop_snm , drop_ssb , LAST_ENTRY /* Should be last entry */ }; const char* drop_options_s[LAST_ENTRY] = {"drop_ssm", "drop_snm", "drop_ssb"}; 

when you need a string representation of an enumeration, you can drop_options_s[enum];

+10
source

Using X-Macro :

file items :

 ITEM(drop_ssm) ITEM(drop_snm) ITEM(drop_ssb) 

A source:

 #define ITEM(A) A, enum drop_options_e { #include "items" last }; #undef ITEMS #define ITEM(A) #A, char item_names[] = { #include "items" NULL}; 

So now item_names[drop_ssm] will provide you with the text string "drop_ssm"

+4
source

C does not support this. You will need to have a key or equivalent somewhere.

+3
source

If you have a compiler that supports designated C99 initializers, you can improve on Naveen 's answer :

 enum drop_options_e { drop_ssm, drop_snm, drop_ssb }; #define ENUM_TO_S(e) [e] = #e const char *drop_options_s[] = { ENUM_TO_S(drop_ssm), ENUM_TO_S(drop_snm), ENUM_TO_S(drop_ssb) }; 

(With this method, you don’t have to worry about the fact that the array initializers are in the same order as the enum values).

+3
source

There is nothing worth it. You can do very interesting things with macros and Boost.Preprocessor, but it's quite complicated, and I'm not sure how well it will work in C; I did something in C ++ that let me write, for example:

 ENUM( ColorComponent, (red) (green) (blue) (alpha) ); // ... ColorComponent cc = ColorComponent_red; std::cout << "Color: " << toString(cc) << "\n"; 
+2
source

The best way I've come across is to create an array of translations. Sort of:

 struct { enum drop_options_e value; char *string; } TranslationArray[] = { drop_ssm, "drop_ssm", drop_snm, "drop_snm", drop_ssb, "drop_ssb", }; 

This can be problematic if you list a sufficiently large number.

+2
source

I really liked all the answers here! During testing, I found something very short and pleasant with the boost macro BOOST_PP_STRINGIZE:

 //Define the enum you need typedef enum { INTEGER = 0, STRING = 1, BOOLEAN = 2, }eValueType; // Then in code use BOOST_PP_STRINGIZE, for example: char* valueTypeStr = BOOST_PP_STRINGIZE(INTEGER); 
-1
source

Source: https://habr.com/ru/post/1305515/


All Articles