Notes

Thoughts, write-ups, and things worth remembering.

Function pointers

#cpp#pointers#functional Updated Sep 16, 2026

A variable that holds the address of a function, and can be called through.

int add(int a, int b) { return a + b; }

int (*fp)(int, int) = add;   // fp points at add
fp(2, 3);                     // 5 - calls through the pointer

The declaration syntax is famously ugly — int (*fp)(int, int) reads as “fp is a pointer to a function taking two ints and returning int.” using makes this readable:

using BinaryOp = int(*)(int, int);
BinaryOp fp = add;

Why you’d reach for a lambda or std::function instead today

void sortWith(int (*cmp)(int, int));   // can ONLY take a real function - no
                                        // capturing lambda, no member function
void sortWith(std::function<int(int,int)> cmp);   // takes anything callable

A raw function pointer can’t hold a lambda that captures anything, or a bound member function. Lambdas and std::function are the modern default; function pointers mostly show up now when interfacing with C APIs, which don’t know what a lambda is.

Lambda expressions
Callback functions