Teach your old C preprocessor a new trick

How many times has this happened to you: it's late at night, you're debugging code that uses an enum that means something to the app but totally meaningless to you, and the output prints a whole bunch of enum values, and you have no clue what they stand for?

Well, it happened to me once too many times, and I looked around for a solution that didn't involve maintaining two separate lists - one of the enums and one of their string values. That was a potential debugging headache waiting to happen, and it certainly wasn't elegant! Since I didn't find anything suitable, I came up with this solution that uses the C preprocessor's stringize operator, and lets you maintain only one copy of the enum values for easy editing. The solution extends the X Macro pattern. Note that this is in the Objective C flavor, and you'll need to remove the '@' (string literal) operator if you're not using Objective C.

First, the definition:

#define ENUM_TABLE \X(ENUM_ONE),    \
X(ENUM_TWO)    \

#define X(a)    a
typedef enum Foo {
} MyFooEnum;
#undef X

#define X(a)    @#a
NSString * const enumAsString[] = {
#undef X

Now, to use it, it's fairly straightforward:

MyFooEnum t = ENUM_ONE;
NSLog(@"Enum test - t is: %@", enumAsString[t]);

NSLog(@"Enum test - t is now: %@", enumAsString[t]);

which outputs:

2014-10-22 13:36:21.344 FooProg[367:60b] Enum test - t is: ENUM_ONE
2014-10-22 13:36:21.344 FooProg[367:60b] Enum test - t is now: ENUM_TWO

I hope it eases your debugging!