Suppose the report needs to count long sessions, then short sessions, then sessions for one topic. You could write three loops that differ in a single condition. Then a bug fix in the loop, such as a corrected bound, has to be made three times, and one copy will be missed. C lets you separate the part that varies from the part that stays the same: write the loop once and pass the condition in as a function pointer, a value that refers to a function. The function you pass is called a callback, because the loop calls back into your code.
You will use this twice more in this course: qsort takes a comparison callback in the next lesson, and Day 6's allocator is a pair of callbacks that tests can replace.
Predict and run
Read the program before pressing Run. Write down its output and say which function runs when test(3) is evaluated.
#include <stdio.h>
typedef int (*Predicate)(int);
int positive(int value) { return value > 0; }
int main(void) {
Predicate test = positive;
printf("%d %d\n", test(3), test(-1));
return 0;
}Check your prediction
1 0test holds a pointer to positive, so calling test(3) runs positive(3). A function name used as a value converts to a pointer to that function, the way an array name converts to a pointer to its first element.
Reading the type
typedef int (*Predicate)(int); names the type "pointer to a function that takes an int and returns an int". The parentheses around *Predicate matter: without them, int *Predicate(int) would declare a function returning int *. The typedef keeps later signatures readable. Without it, a parameter reads int (*test)(int).
Write the loop once
#include <stdio.h>
#include <stddef.h>
typedef int (*Predicate)(int);
static int is_long(int minutes) { return minutes >= 30; }
static int is_short(int minutes) { return minutes < 15; }
size_t count_matches(const int values[], size_t count, Predicate test) {
size_t found = 0;
for (size_t i = 0; i < count; ++i) {
if (test(values[i])) { ++found; }
}
return found;
}
int main(void) {
int minutes[5] = {25, 40, 10, 60, 5};
printf("long: %zu\n", count_matches(minutes, 5, is_long));
printf("short: %zu\n", count_matches(minutes, 5, is_short));
return 0;
}long: 2
short: 2The loop's bound and its counter are written once. A new rule is just a new small function.
Rules that need data: the context pointer
What if the threshold should come from the user, say "at least 20 minutes"? A predicate that takes only the value cannot see it. A global variable would work but hides an input: the result of count_matches would depend on state not visible at the call site, and two callers wanting different thresholds would trample each other.
The standard C answer is an extra void *context parameter. The caller passes a pointer to whatever data the callback needs; the loop passes it through without looking at it; the callback converts it back to the real type:
#include <stdio.h>
#include <stddef.h>
typedef int (*Test)(int value, void *context);
typedef struct { int minimum; } Threshold;
static int at_least(int value, void *context) {
const Threshold *threshold = context;
return value >= threshold->minimum;
}
size_t count_if(const int values[], size_t count, Test test, void *context) {
size_t found = 0;
for (size_t i = 0; i < count; ++i) {
if (test(values[i], context)) { ++found; }
}
return found;
}
int main(void) {
int minutes[5] = {25, 40, 10, 60, 5};
Threshold twenty = {20};
Threshold fifty = {50};
printf("at least 20: %zu\n", count_if(minutes, 5, at_least, &twenty));
printf("at least 50: %zu\n", count_if(minutes, 5, at_least, &fifty));
return 0;
}at least 20: 3
at least 50: 1What the compiler cannot check
void * throws type information away. If the caller passes a pointer to an int but the callback converts it to Threshold *, the compiler accepts it and the access is undefined behavior. Keep the pairing obvious: define the context type right next to the callback that uses it, and pass &thing of exactly that type.
Two more rules belong in a callback contract. Calling through a NULL function pointer is undefined behavior, so either document "must not be NULL" or check it. And calling a function through a pointer of a different function type is also undefined, even if the parameters look similar:
int positive(int value);
Test wrong = (Test)positive; /* compiles because of the cast */
wrong(3, NULL); /* undefined: positive takes one parameter */A cast that silences the compiler is a sign the types disagree. Write a small wrapper with the right signature instead.
Practice
Your turn
Write void for_each(const Record records[], size_t count, Visit visit, void *context), which calls visit(&records[i], context) for each record. Then write two visitors. add_topic uses a context TopicTotal with a topic and a running total, and adds the minutes of matching records. track_longest uses a context Longest and keeps the largest minutes seen. The starter must print reading total: 35, math total: 0 and longest: 40.
#include <stdio.h>
#include <string.h>
typedef struct { char topic[24]; int minutes; } Record;
typedef void (*Visit)(const Record *record, void *context);
typedef struct { const char *topic; long total; } TopicTotal;
typedef struct { int max; } Longest;
/* Write for_each, add_topic and track_longest here. */
int main(void) {
const Record records[3] = {{"reading", 25}, {"coding", 40}, {"reading", 10}};
TopicTotal reading = {"reading", 0};
TopicTotal math = {"math", 0};
Longest longest = {0};
for_each(records, 3, add_topic, &reading);
for_each(records, 3, add_topic, &math);
for_each(records, 3, track_longest, &longest);
printf("reading total: %ld\n", reading.total);
printf("math total: %ld\n", math.total);
printf("longest: %d\n", longest.max);
return 0;
}Hint 1: the idea
The visitor has no return value, so any result it produces must be stored in the context. That is why the contexts are separate structs owned by main, which reads them after the loop.
Hint 2: a first step
Write for_each and a visitor that only prints each record's topic, with NULL as its context, and run: three topics, in order. Then write add_topic and decide the first line of its body: how does a void * become the TopicTotal * that main passed in?
Show one solution
#include <stdio.h>
#include <string.h>
typedef struct { char topic[24]; int minutes; } Record;
typedef void (*Visit)(const Record *record, void *context);
typedef struct { const char *topic; long total; } TopicTotal;
typedef struct { int max; } Longest;
void for_each(const Record records[], size_t count, Visit visit, void *context) {
for (size_t i = 0; i < count; ++i) {
visit(&records[i], context);
}
}
static void add_topic(const Record *record, void *context) {
TopicTotal *sum = context;
if (strcmp(record->topic, sum->topic) == 0) { sum->total += record->minutes; }
}
static void track_longest(const Record *record, void *context) {
Longest *longest = context;
if (record->minutes > longest->max) { longest->max = record->minutes; }
}
int main(void) {
const Record records[3] = {{"reading", 25}, {"coding", 40}, {"reading", 10}};
TopicTotal reading = {"reading", 0};
TopicTotal math = {"math", 0};
Longest longest = {0};
for_each(records, 3, add_topic, &reading);
for_each(records, 3, add_topic, &math);
for_each(records, 3, track_longest, &longest);
printf("reading total: %ld\n", reading.total);
printf("math total: %ld\n", math.total);
printf("longest: %d\n", longest.max);
return 0;
}reading total: 35
math total: 0
longest: 40for_each never learns what the visitors compute. It only promises to visit each active record once, in order. Each visitor's state lives in a context that main owns and that outlives the call, so the callback never holds a pointer to something that has ended. Starting max at 0 works because valid durations are at least 1. Next, qsort uses the same idea with a comparison callback that must follow strict rules.
Completion is saved in this browser only. It does not measure mastery.