c language · medium

C: Function Pointers & Callbacks

A function pointer stores the address of a function so it can be called indirectly, and its declaration must put the name in parentheses: int (*fp)(const void*, const void*); reads as 'fp is a pointer to a function taking two const void* and returning int', whereas int *f(...) would be a function returning int* — a classic parsing puzzle that a typedef (typedef int (*Cmp)(...);) makes readable. A function name decays to its address, so fp = cmp and fp = &cmp are equivalent, and you may call through the pointer as fp(a, b) or (*fp)(a, b); the pointer's type must match the function's signature exactly, since calling through an incompatible type is undefined behavior. Their main purpose is callbacks — passing behavior as data — exemplified by qsort and bsearch comparators that let one routine work for any element type and ordering, as well as event handlers, state machines built as arrays of handlers, and C-style polymorphism via a struct of function pointers (precisely how C++ vtables work underneath). Because plain qsort carries no context, context-bearing callbacks pass a separate void* user-data argument (as in the qsort_r/qsort_s variants).

🔑 Key line

C function pointers store a function's address (int (*fp)(args) — inner parens essential); a function name decays to &func, call via fp(a,b) or (*fp)(a,b) with exact signature match; they enable callbacks (qsort comparator) and C-style polymorphism (struct of function pointers).

The code

int cmp(const void* a, const void* b) {
return (*(int*)a) - (*(int*)b); // (careful: can overflow)
}
int (*fp)(const void*, const void*) = cmp; // pointer to function
qsort(arr, n, sizeof *arr, fp); // callback into qsort
typedef int (*Cmp)(const void*, const void*); // readable alias
Cmp c = cmp; // function name decays to &function
c(&x, &y); // call through the pointer (== (*c)(&x,&y))

What this lesson walks through

  1. 01Declaring a pointer to a function
  2. 02Assigning and calling
  3. 03Gotcha — declaration syntax + signature casts
  4. 04Callbacks: the qsort pattern

A function pointer stores the address of a function so you can call it indirectly. The declaration syntax puts the name in parentheses: int (*fp)(const void*, const void*); means 'fp is a pointer to a function taking two const void* and returning int'. Without the inner parentheses, int *f(...) would be a function returning int* — a classic C reading puzzle. A typedef makes it readable.

See it animated — step by step, at your own pace

Unlock the full interactive walkthrough of C: Function Pointers & Callbacks and 100+ animated C++ interview lessons.

← Previous
C: malloc / free & Heap Bugs
Next →
C: Preprocessor Macro Pitfalls