c / intermediate
Snippet
Function Pointers for Callbacks
Function pointers allow you to pass functions as arguments to other functions, enabling flexible and generic code patterns like callbacks.
snippet.c
1
2
3
4
5
6
7
int add(int a, int b) { return a + b; }int execute(int (*op)(int, int), int x, int y) {return op(x, y);}int result = execute(add, 5, 3);
Breakdown
1
int (*op)(int, int)
Declares a pointer named 'op' that points to a function taking two ints and returning an int.
2
return op(x, y);
Calls the function being pointed to by 'op' with the provided arguments.
3
execute(add, 5, 3)
Passes the address of the 'add' function to the 'execute' function.