Store four arithmetic functions in an array of function pointers and run a list of menu choices against it, rejecting invalid choices.
#include <stdio.h>
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int mul(int a, int b) { return a * b; }
int mod(int a, int b) { return a % b; }
int main(void) {
int (*menu[])(int, int) = {add, sub, mul, mod};
const char *names[] = {"add", "sub", "mul", "mod"};
int choices[] = {0, 2, 3, 7};
for (int i = 0; i < 4; i++) {
int c = choices[i];
if (c < 0 || c >= 4) {
printf("choice %d: invalid\n", c);
continue;
}
printf("%s(17, 5) = %d\n", names[c], menu[c](17, 5));
}
return 0;
}
add(17, 5) = 22 mul(17, 5) = 85 mod(17, 5) = 2 choice 7: invalid
Indexing the array replaces a switch. The bounds check matters: calling through an out-of-range element would jump to a garbage address.