c / intermediate
Snippet
Function Pointers for Callbacks
Function pointers allow functions to be passed as arguments, enabling generic programming patterns. Here, 'mathOperation' doesn't know what it will do with 'a' and 'b' until it receives a pointer to the specific function at runtime.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>void mathOperation(int a, int b, int (*operation)(int, int)) {printf("Result: %d\n", operation(a, b));}int add(int x, int y) { return x + y; }int multiply(int x, int y) { return x * y; }int main() {mathOperation(5, 3, add);mathOperation(5, 3, multiply);return 0;}
Breakdown
1
int (*operation)(int, int)
Defines a pointer named 'operation' to a function taking two ints and returning an int.
2
operation(a, b)
Calls the function pointed to by the 'operation' pointer.
3
mathOperation(5, 3, add);
Passes the address of the 'add' function as the third argument.