#include <stdio.h>
#include <string.h>
typedef enum{
RED = 0xff,
GREEN = 0xff00,
BLUE = 0xff0000
}PRE_DEFINED_COLORS;
typedef struct{
int color_val;
char *color_name;
}COLOR_ENTRY;
#define COLOR_ITEM(a) {a, #a}
COLOR_ENTRY color_entries[]={
COLOR_ITEM(RED),
COLOR_ITEM(GREEN),
COLOR_ITEM(BLUE)
};
#define DEFINED_COLOR_COUNT (sizeof(color_entries)/sizeof(*color_entries))
int GetEnumValue(const char *color_name , int errval){
for(int i = 0 ; i < DEFINED_COLOR_COUNT ; i++)
if(!strcmp(color_entries[i].color_name , color_name))
return color_entries[i].color_val;
//in case not found return errval
return errval;
}
const char *GetEnumName(int color_val){
for(int i = 0 ; i < DEFINED_COLOR_COUNT ; i++)
if(color_entries[i].color_val == color_val)
return color_entries[i].color_name;
//no match, return NULL
return NULL;
}
int main(void){
printf("Printing defined color table (by index):\n");
for(int i = 0 ; i < DEFINED_COLOR_COUNT ; i++){
printf(" %d - %-8s= %06X\n", i , color_entries[i].color_name , color_entries[i].color_val);
}
printf("\nPrinting color values by name:\n");
printf(" * %-8s= %06X\n", "RED", GetEnumValue("RED", -1));
printf(" * %-8s= %06X\n", "GREEN", GetEnumValue("GREEN", -1));
printf(" * %-8s= %06X\n", "BLUE", GetEnumValue("BLUE", -1));
// this item do not exists, this will return -1 (0xFFFF:FFFF)
printf(" * %-8s= %06X\n", "YELLOW", GetEnumValue("YELLOW", -1));
return 0;
}