Associating Enums with Strings in C

I saw this link

How to convert rename names to string in c

I have a series enumsdefined as follows in the client library header file (which I cannot change):

Also, transfers are sparse.

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

I want to print these values ​​in my function, for example, I would like to print ERROR_NONEinstead 59. Is there a better way to just use constructs switch caseor if elseto do this? 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 */
+5
source share
2 answers

A direct application of the gating operator may be useful.

#define stringize(x) #x

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

, . :), X

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.

. , , , switch-case - , , enums.

+3

FAQ 11.17. xstr(). , :

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

 printf("%s\n", xstr(ERROR_A));
+1

All Articles