1

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

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

?

w.b
  • 11,026
  • 5
  • 30
  • 49
  • I'm not sure what you expect to get for an enum name in C or looping through it. Enums are just constant values. Would you mind elaborating on the use case? – Benjamin Gruenbaum Nov 17 '13 at 15:21
  • Something like `Enum.GetValues` or `Enum.GetNames` in C# - I'm just curious if it's possible in C. – w.b Nov 17 '13 at 15:23
  • No, it's not. C# has a notion of enum types in run time that C does not have. Just think of C enums as integer values. You can loop through the values in a normal for loop `for(i=FIRSTVALUE,i – Benjamin Gruenbaum Nov 17 '13 at 15:25
  • possible duplicate of [Get enum value by name](http://stackoverflow.com/questions/18070763/get-enum-value-by-name) – hyde Nov 17 '13 at 15:35

2 Answers2

5

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
The Mask
  • 17,007
  • 37
  • 111
  • 185
2

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.

Community
  • 1
  • 1
hyde
  • 60,639
  • 21
  • 115
  • 176