C
Function pointer parameter
Learn to pass function pointers to functions.
Passing a function pointer to a function
A function can take another function's pointer as a parameter. This way the caller chooses the behavior to invoke. Syntax: void apply(int x, int (*op)(int)).
Example: apply(5, square) or apply(5, negate) cause the op(x) line inside apply to call different functions. This pattern underlies standard library functions like qsort: the sort algorithm is fixed, the caller supplies the comparison. This is called a callback; you'll see more in the qsort lesson.
Same function, different behavior
A function pointer parameter lets you call the same function with different behaviors. The apply function stays fixed; you only change the second argument.
For example, write int double_it(int x) and int negate(int x). Calling apply(5, double_it) prints 10; apply(5, negate) prints -5. The body of apply never changes. This reduces code duplication and makes adding new behavior easy: just write a new function and pass it.
Exercise Apply two operations via callback
Write functions int double_it(int x) and int negate(int x) returning x * 2 and -x respectively. Define void apply(int x, int (*op)(int)); inside it print the result of op(x) with printf. In main call apply(5, double_it) and apply(5, negate).
Show example solution
#include <stdio.h>
int double_it(int x) { return x * 2; }
int negate(int x) { return -x; }
void apply(int x, int (*op)(int)) {
printf("%d\n", op(x));
}
int main(void) {
apply(5, double_it);
apply(5, negate);
return 0;
}
Test yourself
-
Complete the callback parameter
void apply(int x, int (____)(int)) {
printf("%d\n", op(x));
}
Show answer
void apply(int x, int (*op)(int)) {
printf("%d\n", op(x));
}
-
Match the callback parts
- apply
- Caller function
- op
- Pointer parameter
- op(x)
- Indirect call
- square
- Passed function
-
What does apply(5, square) do?
- Calls square with 5
- Passes 5 and square to apply; op(5) becomes square(5)
- Merges apply and square
- Adds 5 and square
Show answer
Merges apply and square — 5 and square are passed to apply; inside apply op(5) becomes square(5).
Next lesson: void pointer