Callback patterns
- C course
- Intermediate
- Lesson 27/116
- 5 min
Learn callback patterns and usage.
The callback pattern
A callback is a function passed as a parameter to another function. The caller function invokes the callback at the right time. This is the basis of higher-order functions.
Example: void forEach(int *arr, int n, void (*cb)(int)). This function calls cb(arr[i]) for each array element. The caller chooses what to do via cb. This pattern is standard in event handling, network streams and array processing. qsort itself uses a callback pattern; the comparator is a callback.
Higher-order with forEach
forEach calls the given callback for each array element. The callback decides what to do; forEach decides how to iterate.
Example: void forEach(int *arr, int n, void (*cb)(int)) { for (int i = 0; i < n; i++) cb(arr[i]); }. This function calls cb for each element. If the caller passes print_double as cb, each element is printed doubled; with print_squared, it's squared. The same forEach behaves completely differently with different callbacks. This avoids code duplication.
Practice Write forEach and a callback
Write void print_double(int x) that calls printf("%d\n", x * 2). Define void forEach(int *arr, int n, void (*cb)(int)) that does for (int i = 0; i < n; i++) cb(arr[i]);. In main declare int arr[3] = {1, 2, 3}; and call forEach(arr, 3, print_double);.
Starter code
#include <stdio.h>
// Write print_double
// Define forEach
// Call forEach in main
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
void print_double(int x) {
printf("%d\n", x * 2);
}
void forEach(int *arr, int n, void (*cb)(int)) {
for (int i = 0; i < n; i++) cb(arr[i]);
}
int main(void) {
int arr[3] = {1, 2, 3};
forEach(arr, 3, print_double);
return 0;
}Expected output
2 4 6
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is a callback?
- A function passed to a function Correct answer
- A loop
- A counter
- A data type
Explanation: A callback is a function passed as a parameter to a function.
2 Match the callback uses
| Term | Meaning |
|---|---|
qsort |
Comparator callback |
forEach |
Element callback |
event handler |
Event callback |
comparator |
Sort direction |
3 Complete the forEach call
int arr[3] = {1, 2, 3};
____(arr, 3, print_double);
int arr[3] = {1, 2, 3};
forEach(arr, 3, print_double);
Explanation: forEach iterates and calls the callback.