5

I have seen this link

How to convert enum names to string in c

I have a series of enums defined in the following manner in client provided library header file (which I can't change):

Also the enums are sparse .

typedef enum
{
    ERROR_NONE=59,   
    ERROR_A=65,  
    ERROR_B=67
}

I want to print these values in my function for instance I would like to print ERROR_NONE instead of 59. Is there a better way of just using switch case or if else constructs to get this done ? Example

   int Status=0;
   /* some processing in library where Status changes to 59 */
   printf("Status = %d\n",Status); /* want to print ERROR_NONE instead of 59 */
Community
  • 1
  • 1
user1377944
  • 425
  • 2
  • 5
  • 12
  • Why not use the [stringizing operator](http://msdn.microsoft.com/en-us/library/7e3a913x(v=vs.80).aspx)? Can you show us some code where you are trying to print these enum values? – Pavan Manjunath May 07 '12 at 10:12

2 Answers2

3

A direct application of stringizing operator might be helpful

#define stringize(x) #x

printf("%s\n", stringize(ERROR_NONE));

You've mentioned that you cant change the library file. If you decide otherwise :), you can use X macros as follows

enumstring.c
#include <stdio.h>

#define NAMES C(RED)C(GREEN)C(BLUE)

#define C(x) x,

enum color { NAMES TOP };

#undef C

#define C(x) #x,

const char * const color_name[] = { NAMES };

int main( void ) 
{ printf( "The color is %s.\n", color_name[ RED ]);  
  printf( "There are %d colors.\n", TOP ); }

stdout
The color is RED. 
There are 3 colors.

Read more here

EDIT: With the specific example you are showing us, I am afraid, switch-case is the nearest you can get, especially when you have sparse enums.

Pavan Manjunath
  • 27,404
  • 12
  • 99
  • 125
  • You need a two step macro to force both expansion and stringization. See http://c-faq.com/ansi/stringize.html. – dirkgently May 07 '12 at 10:33
2

FAQ 11.17. Use the xstr() macro. You should probably use that:

 #define str(x) #x
 #define xstr(x) str(x)

 printf("%s\n", xstr(ERROR_A));
dirkgently
  • 108,024
  • 16
  • 131
  • 187