Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

associating enums with strings in C

Tags:

c

string

enums

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 */
like image 650
user1377944 Avatar asked May 07 '12 09:05

user1377944


1 Answers

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.

like image 169
Pavan Manjunath Avatar answered Sep 28 '22 05:09

Pavan Manjunath