Example 1 — A dispatch table of operations
Pick an operation by index.
#include <stdio.h>
static int add(int a, int b) { return a + b; }
static int sub(int a, int b) { return a - b; }
static int mul(int a, int b) { return a * b; }
int main(void) {
int (*ops[])(int, int) = {add, sub, mul};
const char *names[] = {"add", "sub", "mul"};
for (int i = 0; i < 3; i++) {
printf("%s(12, 4) = %d\n", names[i], ops[i](12, 4));
}
return 0;
} How It Works
opsis an array of function pointers.- Each element is called like a normal function.
- Adding a new operation only needs a new table entry.
