tags:

views:

109

answers:

6

Hello,

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,

+3  A: 

C has no support for that. You will have to have a switch or equivalent somewhere.

Matthew Flaschen
+8  A: 

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];

Naveen
+2  A: 

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";
Marcelo Cantos
+2  A: 

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.

Jon L
+2  A: 

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).

caf
It is so much better with X-Macros
qrdl
+2  A: 

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"

qrdl
This looks like a good answer. However, for simplicity I will have to go for Naveen answer.
robUK