Function pointer parameter
- C course
- Intermediate
- Lesson 4/116
- 5 min
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.
Practice 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).
Starter code
#include <stdio.h>
// Write double_it and negate
// Define apply
// Call apply both ways in main
int main(void) {
return 0;
}Sample 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;
}Expected output
10 -5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the callback parameter
void apply(int x, int (____)(int)) {
printf("%d\n", op(x));
}
void apply(int x, int (*op)(int)) {
printf("%d\n", op(x));
}
Explanation: (*op) marks the pointer; (int) is the parameter list.
2 Match the callback parts
| Term | Meaning |
|---|---|
apply |
Caller function |
op |
Pointer parameter |
op(x) |
Indirect call |
square |
Passed function |
3 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 Correct answer
- Adds 5 and square
Explanation: 5 and square are passed to apply; inside apply op(5) becomes square(5).