double add(double a, double b) {
return a + b;
}
double subtract(double a, double b) {
return a - b;
}
double multiply(double a, double b) {
return a * b;
}
double divide(double a, double b) {
return a / b;
}
//typedef gives the pointer type a short name
typedef double (*Operation)(double, double);
//a table of functions: the index picks one
Operation operations[] = {add, subtract, multiply, divide};
double product = operations[2](6, 3);
//product is 18
//a table of commands: the symbol picks the function
typedef struct {
char symbol;
Operation apply;
} Command;
Command commands[] = {
{'+', add}, {'-', subtract}, {'*', multiply}, {'/', divide}
};
size_t count = sizeof commands / sizeof commands[0];
char symbol = '/';
double result = 0;
for (size_t i = 0; i < count; i++) {
if (commands[i].symbol == symbol) {
result = commands[i].apply(7, 2);
break;
}
}
//result is 3.5
printf("product is %g\n", product);
printf("result is %g\n", result);