C
Summary - Function pointers
Combine qsort, callback and dispatch table to write a command handler.
Designing a command handler
In this summary you'll combine qsort, callback and dispatch table concepts to write a command handler. The command handler calls the matching function by command name.
The structure: define add, sub and mul functions. Collect them in a function pointer array. Then call each in turn and print the result. Thanks to the dispatch table, adding a new command is just appending an element to the array; the calling logic stays the same. This is the core pattern of real command-line apps and interpreters.
Exercise Write a command handler
Write int add(int a, int b), int sub(int a, int b) and int mul(int a, int b). Declare a function pointer array with int (*ops[3])(int, int) = {add, sub, mul};. Call all three commands: printf("%d\n", ops[0](3, 4));, printf("%d\n", ops[1](10, 7)); and printf("%d\n", ops[2](2, 5));.
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 mul(int a, int b) { return a * b; }
int main(void) {
int (*ops[3])(int, int) = {add, sub, mul};
printf("%d\n", ops[0](3, 4));
printf("%d\n", ops[1](10, 7));
printf("%d\n", ops[2](2, 5));
return 0;
}
Summary
In this group you learned function pointers in depth. You saw the definition, two call forms, use with qsort, the callback pattern and the dispatch table.
You combined these to write a command handler. qsort callback, forEach callback and dispatch table; all three are different uses of function pointers. These patterns are common in real-world C code: event handling, sorting, command processing and interpreters. In the next groups these foundations will be used on more complex data structures and systems programming.
Test yourself
-
What's the best use case for a dispatch table?
- Math calculations
- Memory allocation
- Command handlers
- String concatenation
Show answer
Command handlers — Command handlers are the best use case for dispatch tables.
-
Match the concepts to use
- qsort
- Comparator callback
- forEach
- Element callback
- ops[0](...)
- Dispatch call
- int (*fp)(int)
- Pointer type
Next lesson: Structs and pointers