/** * Example showing a use of arrays of function pointers * The core idea here is that by putting the function pointers into an array * you can cleverly avoid sets of cumbersome if statements * * @author gtowell * Created: April 2021 * **/ #include #include #include #ifndef NULL #define NULL (void *)0 #endif // typedef for my function pointers typedef int(*myfuns)(int, int); /** * Apply the operation passed in as a function pointer to the * other params * @param f -- a pointer to a function. The function must return * an int and it must take two ints as param * @param a -- an int * @param b -- another int * @return the value that result from applying the passed function * to the two params * **/ int op(int (*f)(int, int), int a,int b) { return (*f)(a, b); } /** * Multiply two integers * @param a an integer * @param b another integer * @return the product of the two integers * **/ int mult(int a, int b) { return a * b; } /** * Divide two integers but go UP if remainder > 0. * @param a an integer * @param b another integer * @return Divide two integers but go UP if remainder > 0. * **/ int divU(int a, int b) { return (a / b) + ((a % b == 0) ? 0 : 1); } /** * Normal integer division * @param a an integer * @param b another integer * @return Divide two integers. * **/ int divV(int a, int b) { return (a / b); } /** * get input from the user. This input is assumed to be of the form * OP i i * where OP is ether m, d or u or q * and i is an integer * This program is fragile. * **/ int main(int argc, char const *argv[]) { myfuns funarr[128]; funarr['m'] = *mult; funarr['*'] = mult; funarr['d'] = divV; funarr['u'] = divU; char lin[256]; char op; int v1; int v2; while (fgets(lin, 255, stdin)) { sscanf(lin, "%c %d %d", &op, &v1, &v2); if (op=='q') break; printf("%d\n", (funarr[op])(v1, v2)); } return 0; }