Function Pointer Tables
Dispatch patterns.
Tables of Functions
You can store function pointers in an array to build a dispatch table. An index or code selects which function to run, replacing long if-else or switch chains.
#include <stdio.h>
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int main(void) {
int (*ops[2])(int,int) = { add, sub };
printf("%d\n", ops[0](5, 3));
printf("%d\n", ops[1](5, 3));
return 0;
}Indexing the Table
Pick an operation at runtime by indexing the array. The index can come from user input or program state.
#include <stdio.h>
int mul(int a, int b) { return a * b; }
int add(int a, int b) { return a + b; }
int main(void) {
int (*ops[2])(int,int) = { add, mul };
int choice = 1;
printf("%d\n", ops[choice](6, 7));
return 0;
}All lessons in this course
- Declaring Function Pointers
- Passing Functions
- qsort with Comparators
- Function Pointer Tables