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 */
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With