While coding C programming, there will be scenarios where you want to print the enum values as string while debugging. There are methods where you can define separate function which will return the string of definition, but the issue with that is , when you edit code, if we add a new enum value and forgot to add in the string conversion function/array, it will be give lot of problems and spend time on debugging
After googling, i found on solution which has only one definition, I edited it to suit my requirements. Please check the code below
#include<stdio.h>
#define FOREACH_WEEKDAYS(WEEKDAYS) \
WEEKDAYS(SUNDAY) \
WEEKDAYS(MONDAY) \
WEEKDAYS(TUESDAY) \
WEEKDAYS(WEDNESDAY) \
WEEKDAYS(THURSDAY) \
WEEKDAYS(FRIDAY) \
WEEKDAYS(SATURDAY)
#define GENERATE_ENUM(ENUM) ENUM,
#define GENERATE_STRING(STRING) #STRING,
enum WEEKDAYS_ENUM {
FOREACH_WEEKDAYS(GENERATE_ENUM)
};
static const char *GET_WEEKDAY_STRING[] = {
FOREACH_WEEKDAYS(GENERATE_STRING)
};
int main()
{
printf("enum SUNDAYas a string: %s enum(int): %d\n", GET_WEEKDAY_STRING[SUNDAY], SUNDAY);
printf("enum TUESDAY as a string: %s enum(int): %d\n", GET_WEEKDAY_STRING[TUESDAY], TUESDAY);
return 0;
}
OUTPUT as below
enum SUNDAY as a string: SUNDAY enum(int): 0
enum TUESDAY as a string: TUESDAY enum(int): 2
The below code after the preprocessing will look like(gcc -E)
enum WEEKDAYS_ENUM {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY,
};
static const char *GET_WEEKDAY_STRING[] = {
"SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY",
};
Comments
Post a Comment