C Programming • C17 baseline, standards-specific features labeled
Function Pointers and Callbacks
Pass behavior to library functions through a callback with a matching function type.
A function pointer stores the address of a function with a particular parameter and return type. Libraries such as qsort accept callbacks so the caller can define ordering. A callback must match the required signature exactly.
Example
#include <stdlib.h>
static int compare_ints(const void *left, const void *right) {
int a = *(const int *)left;
int b = *(const int *)right;
return (a > b) - (a < b);
}
int main(void) {
int values[] = {7, 2, 5};
qsort(values, sizeof values / sizeof values[0],
sizeof values[0], compare_ints);
}
What to expect
After qsort returns, values is ordered as 2, 5, 7.
Key idea: Match the callback signature and avoid comparator arithmetic that can overflow.