w.b
w.b

Reputation: 11228

enumerating all enum names/values in C

How can I enumerate all enum names and values in C to print it like

printf("Name: %s, value: %d\n", name, value);

?

Upvotes: 1

Views: 447

Answers (2)

The Mask
The Mask

Reputation: 17427

Check out the X macro:

#define COLORS \
    X(Cred, "red") \
    X(Cblue, "blue") \
    X(Cgreen, "green")

#define X(a, b) a,
enum Color { COLORS };
#undef X


#define X(a, b) b,
static char *ColorStrings[] = { COLORS };
#undef X

printf("%s\n", ColorStrings[Cred]); // output: red

Upvotes: 5

hyde
hyde

Reputation: 62838

You can't, at least not directly. There are a few solutions though.

First, if you don't actually need the names, you can simply have an end marker in the enum, if values are sequential:

enum my_vals { FIRST, SECOND, LAST_my_vals };
...
for (enum my_vals it = FIRST ; it < LAST_my_vals ; ++it) {
    ....
} 

But if you do need the names, you can adapt this question: Get enum value by name

Then you will have a array with all the values, and can iterate the array.

Upvotes: 2

Related Questions