C/C++ Arena

Function pointers and callbacks in C

Store a function in a variable, pass it as a callback, and use it with qsort, with readable typedefs.

A function's name, used without calling it, is its address. You can store that in a function pointer and call through it later, which lets code decide what to do at run time.

The syntax int (*op)(int, int) reads as "op is a pointer to a function taking two ints and returning an int". A typedef makes it readable.

Callbacks are how C does customization: qsort takes a comparison function, and event systems take handler functions.

Example

#include <stdio.h>
#include <stdlib.h>

int by_value(const void *a, const void *b) {
    int x = *(const int *)a;
    int y = *(const int *)b;
    return (x > y) - (x < y);
}

int main(void) {
    int v[] = {42, 7, 19, 3};
    qsort(v, 4, sizeof v[0], by_value);
    printf("%d %d %d %d\n", v[0], v[1], v[2], v[3]);
    return 0;
}

Output:

3 7 19 42

Watch it run: Calling through a function pointer

Practice it