Function Pointers & Callbacks in C
A function pointer holds a function's address, letting behavior itself be passed around: int (*op)(int, int) points at any matching function, called later as op(2, 3). This is C's polymorphism — qsort sorts anything because you supply the comparison, event loops dispatch through handler tables, state machines jump through transition arrays.
The syntax is famously gnarled (return type, parenthesized *name, parameter list), so typedef the pointer type once (typedef int (*cmp_fn)(const void*, const void*);) and use the name everywhere. Add a void* context parameter alongside and callbacks can carry state too.
Declare with the star inside
int (*op)(int, int) = add; — parenthesized *op distinguishes pointer-to-function from function-returning-pointer.
Call through transparently
op(2, 3) invokes whatever op points at — call sites never care which function is installed.
typedef the type once
A named cmp_fn type replaces the gnarled spelling everywhere — declarations become readable overnight.
Pair with void* context
Callbacks taking (args..., void *ctx) let callers smuggle state through generic interfaces — the C closure idiom.
#include <stdio.h> int add(int a, int b) { return a + b; }int mul(int a, int b) { return a * b; } int main(void) { int (*op)(int, int) = add; printf("%d\n", op(2, 3)); op = mul; printf("%d\n", op(2, 3)); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.