Learn C
#include "functions/function_pointers.h"

Function Pointers & Callbacks in C

#concept

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.

#how it works
1

Declare with the star inside

int (*op)(int, int) = add; — parenthesized *op distinguishes pointer-to-function from function-returning-pointer.

2

Call through transparently

op(2, 3) invokes whatever op points at — call sites never care which function is installed.

3

typedef the type once

A named cmp_fn type replaces the gnarled spelling everywhere — declarations become readable overnight.

4

Pair with void* context

Callbacks taking (args..., void *ctx) let callers smuggle state through generic interfaces — the C closure idiom.

#example
#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;
}
Output
5
6
1op first points at add — calling through it computes 2 + 3 = 5.
2Reassigning to mul swaps behavior at run time with no type change.
36 prints second — same call expression, new function, decided while running.
#use cases
qsort comparators customizing sort order per call site
Dispatch tables replacing switch forests in interpreters and drivers
Callback APIs (event handlers, traversals) with void* context
State machines as arrays of handler pointers indexed by state

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.