views:

73

answers:

4

Is there a method to return the identifier string for a given element's numerical value? For instance, logging a UITouch's phase returns an int, but having the actual string value would be easier to read.

I suppose I could write my own switch statement to do this, but I'm hoping there's a built-in means.

A: 

No, not in C. You have to write your own.

pmg
A: 

In C there isn't any builtin. In C99, the enumeration constants aren't even of enum type but int.

Jens Gustedt
+5  A: 

No. But if you're looking for a relatively-neat way of maintaining your own solution to this (e.g. a switch statement), you could investigate X-macros (see e.g. http://www.drdobbs.com/184401387).

Oli Charlesworth
The sheer amount of cool that can happen with the preprocessor is stunning – thanks for the link!
Mark McDonald
I get very worried when people start to talk about amazingly cool stuff happening with the preprocessor.
Blank Xavier
A: 

Directly it is impossible what you want, but probably following code could help you as a workaround

#include <stdio.h>

#define strFromAnything( x ) ( #x )

int main()
{
    typedef enum _tagTestEnum {
        Test1,
        BlaBla,
        HaHa
    } TestEnum;
    char* TestEnumToStr[] = {
        strFromAnything(Test1),
        strFromAnything(BlaBla),
        strFromAnything(HaHa),
    };

    TestEnum test = BlaBla;

    printf("%d: %s", test, TestEnumToStr[test]);

    return 0;
}

It will produce output:

1: BlaBla
Oleg