/* Filename: color_test.c * Purpose: Show usage of function pointers in a small example * that shows having handlers to processing certain colors * in a small little program * Author: Alain Hoang */ #include #include #include /** Function declarations **/ int handle_orange(char *str); int handle_red(char *str); int handle_green(char *str); int handle_blue(char *str); int handle_yellow(char *str); /** Globals **/ /* An enum to hold all the types of colors. END is a special type that * signifies the end * * enums are ints by default * * Might have been useful to use a typedef on the enum type */ enum { ORANGE, /* ORANGE = 0 */ RED, /* RED = 1 */ GREEN, /* GREEN = 2 */ BLUE, /* BLUE = 3 */ YELLOW, /* YELLOW = 4 */ END /* END = 5 */ }; /* The struct we're using to hold the color type and the test to run when * we see that color type */ struct colors { int type; /* What color type am I */ int (*color_handler)(char *); }; /* Define a table of for determining which type of color it is. * The first field in the struct determines the color type * The second field is a pointer to a function which handles what to do * with the color */ struct colors color_table[] = { { ORANGE, handle_orange }, { RED, handle_red }, { GREEN, handle_green }, { BLUE, handle_blue }, { YELLOW, handle_yellow }, { END, 0 } }; int main(int ac, char *av[]) { int i; /* Argument parsing. Make sure appropriate args and that the type * doesn't exceed the number of known types */ if (ac != 3) { printf("Usage: fp_test "); exit(1); } if (atoi(av[1]) >= END) { printf("Type is too large. Try a value smaller than %d\n", END); exit(1); } /* Loop through the table and find the appropriate type. If we find one * then we call that handler with the 3rd argument as the name */ for (i = 0; color_table[i].type != END; i++) { if(color_table[i].type == atoi(av[1])) { color_table[i].color_handler(av[2]); } } return 0; } /* * Handlers for the colors. All follow the same structure. * args: str - A string identifying the name of the object * returns: An int, 0 means success * * NOTES: It might be better to put all the handlers in their own file * for slightly better modularization. */ int handle_orange(char *str) { printf("%s is orange\n", str); return 0; } int handle_green(char *str) { printf("%s is green\n", str); return 0; } int handle_red(char *str) { printf("%s is red\n", str); return 0; } int handle_blue(char *str) { printf("%s is blue\n", str); return 0; } int handle_yellow(char *str) { printf("%s is yellow\n", str); return 0; }