![]() |
| | #1 |
| Registered User Join Date: Jun 2005
Posts: 28
| Printing enum field symbolically |
| pdc is offline | |
| | #2 |
| Registered User Join Date: Mar 2003
Posts: 3,903
| Nothing like this exists as a compiler extension to GCC (that I can find). The only thing close is the Function Names as Strings extension. You're better off doing it in a portable fashion: Code: #include <stdio.h>
typedef enum
{
value_1,
value_2,
value_3,
} MyEnum;
/*---------------------------------------------------------------------------*/
#ifndef NDEBUG
/*---------------------------------------------------------------------------*/
typedef struct
{
MyEnum val;
const char *val_name;
} MyEnum_TxtMap;
static const MyEnum_TxtMap g_MyEnum_TxtMap[] =
{
{value_1, "value_1"},
{value_2, "value_2"},
{value_3, "value_3"},
};
const char* MyEnum2Text(MyEnum val)
{
const size_t map_sz = sizeof(g_MyEnum_TxtMap) / sizeof(*g_MyEnum_TxtMap);
size_t n = 0;
for (; n < map_sz; ++n)
{
if (g_MyEnum_TxtMap[n].val == val)
return g_MyEnum_TxtMap[n].val_name;
}//for
return "!!invalid MyEnum val!!";
}
/*---------------------------------------------------------------------------*/
#else /* NDEBUG */
/*---------------------------------------------------------------------------*/
const char* MyEnum2Text(MyEnum val)
{
return "!!non-debug build!!";
}
/*---------------------------------------------------------------------------*/
#endif /* NDEBUG */
/*---------------------------------------------------------------------------*/
int main()
{
MyEnum val = value_2;
printf("val = %s\n", MyEnum2Text(val));
return 0;
}
Last edited by Codeplug; 07-04-2005 at 09:29 AM. |
| Codeplug is offline | |
| | #3 |
| Registered User Join Date: Jun 2005
Posts: 28
| Thanks, yeah, I just went with something similar myself in the end. It was always going to be an opportunistic hack, nothing Dijkstra would approve of |
| pdc is offline | |
| | #4 |
| and the hat of Jobseeking Join Date: Aug 2001 Location: The edge of the known universe
Posts: 21,706
| Well if you're consistent enough about how you declare and name things, you should be able to write say a perl script (or other scripting language of your choice) to parse your source code and generate the lookup tables automatically. |
| Salem is offline | |
![]() |
| Thread Tools | |
| Display Modes | |
|
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| how to print enum field literals | patiobarbecue | C++ Programming | 8 | 04-05-2009 08:48 AM |
| Printing values from Enum | Raskalnikov | C Programming | 8 | 02-16-2009 10:28 PM |
| Please critique and suggest improvements for parser | Queue | C Programming | 14 | 09-28-2006 08:28 PM |
| Problem with Visual C++ Object-Oriented Programming Book. | GameGenie | C++ Programming | 9 | 08-29-2005 11:21 PM |
| i am not able to figure ot the starting point of this | youngashish | C++ Programming | 7 | 10-07-2004 02:41 AM |