-1

Friend, there are a lots of enum values

enum{
ABC = 123,
XYZ = 456,
FOO = 4321,
BAR = 98743,
...
}

when I got the value, I want print the enum's NAME. we could create a string , value pair array. but have to repeat literally the enum body. if enum changed, then array has to be changed accordingly. I remember preprocess could do magic, create enum list, also generate string, value array with one body.

hope masters here could give me a guide.

thanks Xian

2 Answers2

2

In my_enum.inc:

MY_ENUM_ITEM(ABC, 123)
MY_ENUM_ITEM(XYZ, 456)
MY_ENUM_ITEM(FOO, 4321)
MY_ENUM_ITEM(BAR, 98743)

Then to define the enum itself use something like:

enum my_enum {
#define MY_ENUM_ITEM(_n, _v) _n = _v,
#include "my_enum.inc"
#undef MY_ENUM_ITEM
};

and to convert from a value to a string:

const char *my_enum_to_string(enum my_enum e) {
    switch (e) {
#define MY_ENUM_ITEM(_n, _v) case _v: return #_n;
#include "my_enum.inc"
#undef MY_ENUM_ITEM
    default: return NULL;
    }
}
jrtc27
  • 8,496
  • 3
  • 36
  • 68
0

Why not use a hashmap, instead of using the C preprocessor?

chutsu
  • 13,612
  • 19
  • 65
  • 86