c / intermediate
Snippet
Dynamic Dispatch via Function Pointers
Function pointers allow functions to be passed as arguments, enabling dynamic behavior at runtime (callbacks).
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>void add(int a, int b) { printf("Sum: %d\n", a + b); }void subtract(int a, int b) { printf("Diff: %d\n", a - b); }void execute(void (*op)(int, int), int x, int y) {op(x, y);}int main() {void (*operation)(int, int) = add;execute(operation, 10, 5);operation = subtract;execute(operation, 10, 5);return 0;}
Breakdown
1
void (*op)(int, int)
Declares a pointer to a function that takes two ints and returns void.
2
op(x, y);
Invokes the function currently pointed to by 'op'.