C
Function pointer array
Learn dispatch tables with function pointer arrays.
Function pointer array
A function pointer array is an array whose elements are function pointers. This structure forms a dispatch table; it selects the function to call based on an index.
Example: int (*ops[2])(int, int) = {add, sub};. This is a two-element function pointer array. Calling ops[0](5, 3) invokes add(5, 3); ops[1](10, 4) invokes sub(10, 4). This pattern replaces a switch-case chain; it makes the code cleaner and more extensible. To add a new operation you just append an element to the array.
The dispatch table advantage
The dispatch table is cleaner than a switch-case chain. To add a new operation you just append to the array; the calling logic stays the same.
Example: in a calculator, instead of switch (op) { case 0: add(a,b); ... } you write ops[op](a, b). To add a 'mul' operation you append mul to the ops array; the call becomes ops[2](a, b). Unlike switch-case, the dispatch table separates data from behavior; this makes extension easy. This pattern is standard in command-line apps and interpreters.
Exercise Write a calculator
Write int add(int a, int b) and int sub(int a, int b). Declare a function pointer array with int (*ops[2])(int, int) = {add, sub};. Call both operations: printf("%d\n", ops[0](5, 3)); and printf("%d\n", ops[1](10, 4));.
Show example solution
#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](10, 4));
return 0;
}
Test yourself
-
Match operation to function
- ops[0]
- add function
- ops[1]
- sub function
- {add, sub}
- Initializer list
- int (*ops[2])(...)
- Array type
-
Complete the dispatch call
int (*ops[2])(int, int) = {add, sub};
int r = ____[0](5, 3);
Show answer
int (*ops[2])(int, int) = {add, sub};
int r = ops[0](5, 3);
-
What does a dispatch table do?
- Allocates memory
- Calls a function by index
- Reads a file
- Copies a string
Show answer
Calls a function by index — A dispatch table selects the function to call by index.
Next lesson: Summary - Function pointers