Can I display the value of an enum with printf()?

Pieter picture Pieter · Jan 29, 2010 · Viewed 116.1k times · Source

Is there a one-liner that lets me output the current value of an enum?

Answer

bmargulies picture bmargulies · Jan 29, 2010

As a string, no. As an integer, %d.

Unless you count:

static char* enumStrings[] = { /* filler 0's to get to the first value, */
                               "enum0", "enum1", 
                               /* filler for hole in the middle: ,0 */
                               "enum2", "enum3", .... };

...

printf("The value is %s\n", enumStrings[thevalue]);

This won't work for something like an enum of bit masks. At that point, you need a hash table or some other more elaborate data structure.