Can you access the actual identifier from an enum element's numerical value?
Is there开发者_如何学JAVA 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.
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).
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
No, not in C
. You have to write your own.
In C there isn't any builtin. In C99, the enumeration constants aren't even of enum
type but int
.
精彩评论