Skip to content
Tutorials Center
My learning

Topics

C Reference ยท Functions and Scope

Callbacks in C

Reference for callbacks in C: passing function pointers, the user-data void pointer pattern, qsort and bsearch comparators, event handlers and typedefs.

A callback is a function you hand to another function so that it can call yours later. C has no closures or lambdas, so callbacks are function pointers. The library function (or your own) accepts a pointer to a function with an agreed signature and calls it at the right moment: for each element, when an event occurs, to compare two items.

Because a bare function pointer carries no data, callbacks are often paired with a void * user-data parameter. The caller passes any pointer it likes; the library hands it back unchanged on every call, which lets the callback keep state without globals.

C
typedef int (*compare_fn)(const void *a, const void *b);
void qsort(void *base, size_t n, size_t size, compare_fn cmp);

Try it

C qsort and bsearch comparators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C Your own callback API with user data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Syntax

C
typedef return-type (*callback_name)(parameter-types);

void register_handler(callback_name handler, void *user_data);

int plus_one(int n) { return n + 1; }
callback_name cb = plus_one;     /* a function name converts to a pointer */
int r = cb(4);                   /* call through the pointer: (*cb)(4) is the same */
Part Description
callback type Defined with a typedef so signatures stay readable. The callee and the callback must agree exactly on parameter and return types.
void *user_data Optional context pointer supplied by the caller, passed back to the callback.
qsort comparator int (*)(const void *, const void *): negative if the first item sorts before the second, zero if equal, positive if after.

Errors / undefined behavior: calling a function through a pointer of an incompatible type is undefined. A NULL or dangling function pointer crashes when called. A comparator that is inconsistent (not a strict weak ordering, or changing results) makes qsort and bsearch undefined. Converting between function pointers and void * is not guaranteed by ISO C (POSIX requires it).

Usage notes

  • Type the callback. typedef turns int (*)(const void *, const void *) into a readable name, and parameters become compare_fn cmp.
  • Always provide context. Without user_data, the callback needs globals. Document who owns the pointed-to data and how long it must stay valid (asynchronous callbacks may run after the registering function returned).
  • Casts inside comparators. The const void * parameters must be cast to the real element type; for an array of char *, the pointer points to a char * element, as in compare_strings.
  • Don't subtract in comparators. return x - y; can overflow for large int values. Use the (x > y) - (x < y) pattern.
  • qsort is not stable and the order of equal elements is unspecified. For stable sorting add a tie-breaker such as the original index.
  • Re-entrancy. A callback should not modify the container that is calling it (adding to an array during for_each).
  • No capture. A callback cannot see the enclosing function's locals; pass them via user_data. GCC nested functions and Clang blocks are non-standard extensions.
  • Signals and atexit use callbacks too, with severe restrictions on what the callback may do.
  • Performance. Indirect calls cannot always be inlined, so a callback per element costs more than a loop with the code inline. For hot paths, use macros or static inline helpers.