C
Callback patterns
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.
Exercise 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);.
Show example 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;
}
Test yourself
-
What is a callback?
- A function passed to a function
- A loop
- A counter
- A data type
Show answer
A function passed to a function — A callback is a function passed as a parameter to a function.
-
Match the callback uses
- qsort
- Comparator callback
- forEach
- Element callback
- event handler
- Event callback
- comparator
- Sort direction
-
Complete the forEach call
int arr[3] = {1, 2, 3};
____(arr, 3, print_double);
Show answer
int arr[3] = {1, 2, 3};
forEach(arr, 3, print_double);
Next lesson: Function pointer array