gcc 4.4.2 c89
I have the following enum:
enum drop_options_e
{
drop_ssm,
drop_snm,
drop_ssb
};
I am just wondering that is the best way to get the string representation value from the enum.
So basically, instead of returning the value of 0 for drop_ssm, I could get the 'drop_ssm' instead.
Many thanks for any advice,
One way is to do like this:
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 want a string representation of an enum you can drop_options_s[enum];
Using X-Macro technique:
file items
:
ITEM(drop_ssm)
ITEM(drop_snm)
ITEM(drop_ssb)
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 give you text string "drop_ssm"
C has no support for that. You will have to have a switch or equivalent somewhere.
If you have a compiler that supports C99's designated initialisers, you can improve upon 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 array initialisers being in the same order as the enum values).
There's nothing out of the box. You can do some very interesting things with macros and Boost.Preprocessor, but it's quite involved, and I'm not sure how well it would work in C; I've done things in C++ that let me write, e.g.:
ENUM(
ColorComponent,
(red)
(green)
(blue)
(alpha)
);
// ...
ColorComponent cc = ColorComponent_red;
std::cout << "Color: " << toString(cc) << "\n";
The best way I have see to handle this is to create a translation array. Something like:
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're enum is quite large.
I've so liked all answers here! During trying them I've found something very short and nice with BOOST_PP_STRINGIZE macro from boost:
//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);
精彩评论