enum to string

enum to string

使用 switch case

1
2
3
4
5
6
7
8
9
10
11
12
13
14
enum EValue { KZero, KOne, KTwo };

const char* ToString(EValue value)
{
switch (value) {
case KZero:
return "Zero";
case KOne:
return "One";
case KTwo:
return "Two";
}
return "Not Defined";
}

使用陣列索引進行查表

1
2
3
4
5
6
7
enum EValue { KZero, KOne, KTwo };

const char* ToString(EValue value)
{
static char *table[] = { "Zero", "One", "Two" };
return table[value];
}

使用 X Macro 來實作陣列查表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#define VALUE_TABLE \
X(KZero, "Zero") \
X(KOne, "One") \
X(KTwo, "Two")

#define X(a, b) a,
enum EValue { VALUE_TABLE };
#undef X

const char* ToString(EValue value)
{
#define X(a, b) b,
static char *table[] = { VALUE_TABLE };
#undef X
return table[value];
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#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 the preprocessor gets done, you'll have:
// enum FRUIT_ENUM {
// apple, orange, grape, banana,
// };

// static const char *FRUIT_STRING[] = {
// "apple", "orange", "grape", "banana",
// };
printf("enum apple as a string: %s\n",FRUIT_STRING[apple]);

advanced macro

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
enum fruit                                                                   
{
APPLE = 0,
ORANGE,
GRAPE,
BANANA,
/* etc. */
FRUIT_MAX
};

const char * const fruit_str[] =
{
[BANANA] = "banana",
[ORANGE] = "orange",
[GRAPE] = "grape",
[APPLE] = "apple",
/* etc. */
};

printf("enum apple as a string: %s\n", fruit_str[APPLE]);

reference