Callback
A callback is a function pointer the callee invokes when something happens. The caller supplies the function. The library decides when it runs.
Detailed Explanation
qsort's comparator is a callback. So is a signal handler, a pthread_create start routine, and the function you pass to a GUI toolkit for a button press. C's type for that is a function pointer, often paired with a void *userdata so the callback can find the object it belongs to without globals.
typedef void (*on_line)(void *user, const char *line);
void reader_run(FILE *fp, on_line cb, void *user);
Inside reader_run, each line becomes cb(user, line). The library does not include your headers. You do not poll the library for lines. The control is inverted.
Lifetime: the function must remain valid. A pointer to a nested function is a GCC extension. A pointer to a function in a plugin must outlive the registration. The user pointer must remain valid for every invocation. If user is a stack struct, the registration cannot outlive the function. If the callback stores line and line is a stack buffer in the library, you must copy line before returning.
Reentrancy: if the callback calls back into the library, you have a re-entry problem (locks, iterator invalidation). Document whether that is allowed. Signal-handler callbacks have a much shorter list of legal calls.
NULL callbacks are either "do nothing" or a bug. Pick one and check. A library that dereferences a NULL callback is worse than a library that requires one.
Code Examples
#include <stdio.h>
typedef void (*on_int)(void *user, int value);
static void print_int(void *user, int value)
{
FILE *fp = user;
fprintf(fp, "%d\n", value);
}
static void each(const int *a, int n, on_int cb, void *user)
{
for (int i = 0; i < n; i++) {
cb(user, a[i]);
}
}
int main(void)
{
int a[] = { 1, 2 };
each(a, 2, print_int, stdout);
/* prints:
1
2 */
return 0;
}Common Gotchas
Calling a `NULL` callback is undefined behavior unless you documented NULL as sk
Calling a `NULL` callback is undefined behavior unless you documented NULL as skip and checked
`user` dangles if the registrant returns while the library still holds the point
`user` dangles if the registrant returns while the library still holds the pointer
A callback that stores a pointer to the library's stack buffer has a dangling po
A callback that stores a pointer to the library's stack buffer has a dangling pointer after it returns