Function Pointers
A function pointer stores the address of a function, so the code that runs at a call site can be chosen at runtime. It is how C does callbacks, plugins, and dispatch tables.
Detailed Explanation
A compiled function lives at an address, the same way a variable does. A function pointer holds that address. Calling through it runs whatever function it currently points at, which means the decision about which code runs moves from compile time to runtime.
The declaration syntax is where people bounce off. Read it from the name outward:
int (*compare)(const void *, const void *);
Start at compare. The parentheses around *compare bind the * first, so compare is a pointer. To its right is a parameter list, so it points to a function taking two const void *. To the left is int, the return type. Drop the inner parentheses and you get something entirely different: int *compare(const void *, const void *) declares a function returning int *, which is not what you wanted and will produce a confusing error message a few lines later.
Assignment and calling are more forgiving than the declaration suggests. A function name used in an expression decays to a pointer to itself, so compare = strcmp_wrapper; works without &. Writing &strcmp_wrapper is also legal and means the same thing. Calling can be written compare(a, b) or (*compare)(a, b); both are defined to do the same thing. Modern code uses the short forms.
Because the declarations get unreadable fast — an array of them, or one as a return type — name the type with a typedef:
typedef int (*Compare)(const void *, const void *);
Compare table[4]; /* readable */
int (*table2[4])(const void *, const void *); /* the same type, unreadable */
Where you would reach for one. The first is a callback: qsort needs to compare elements and cannot know how, so you hand it the comparison. bsearch, atexit, and signal work the same way, and every event loop and GUI toolkit in C is built on this pattern.
The second is a dispatch table. A long switch on an opcode, a message type, or a command name can become an array or a struct of function pointers indexed by that value. The win is not speed — a switch over dense integers compiles to a jump table anyway — it is that adding a command means adding one table row instead of editing a growing switch in the middle of a file. Interpreters, state machines, and command-line tools use this constantly.
The third is polymorphism by hand. A struct holding function pointers is a vtable; C++ generates one for you, and C code such as the Linux kernel's struct file_operations writes it out explicitly.
What it costs. An indirect call is slightly slower than a direct one, and more importantly the compiler usually cannot inline it or reason across it, so small functions called in a hot loop lose more than the call overhead itself. Modern branch predictors handle a function pointer that keeps hitting the same target well, and handle one that alternates unpredictably poorly. Use them for structure, not for speed, and measure before putting one inside a tight loop.
Two rules worth memorizing. A function pointer and an object pointer are not interconvertible in standard C — void * covers object pointers only, and POSIX has to add its own guarantee so dlsym can work. And calling through a pointer whose type does not match the function's actual type is undefined behavior, not a reinterpreted call.
Code Examples
#include <stdio.h>
#include <string.h>
/* Naming the type once keeps every later declaration readable. */
typedef int (*Operation)(int lhs, int rhs);
static int add(int a, int b) { return a + b; }
static int subtract(int a, int b) { return a - b; }
static int multiply(int a, int b) { return a * b; }
/* A dispatch table: one row per command, instead of a growing switch. */
struct Command {
const char *name;
Operation run;
};
static const struct Command commands[] = {
{ "add", add },
{ "subtract", subtract },
{ "multiply", multiply },
};
static const Operation *lookup(const char *name)
{
size_t count = sizeof commands / sizeof commands[0];
for (size_t i = 0; i < count; i++) {
if (strcmp(commands[i].name, name) == 0) {
return &commands[i].run;
}
}
return NULL; /* unknown command: let the caller decide what to do */
}
int main(void)
{
const Operation *op = lookup("multiply");
if (op == NULL) {
fprintf(stderr, "unknown command\n");
return 1;
}
printf("%d\n", (*op)(6, 7)); /* prints: 42 */
return 0;
}#include <stdio.h>
#include <stdlib.h>
/* qsort is the callback you will meet first. It cannot know how to compare
your elements, so you supply that as a function pointer. */
static int by_length_then_text(const void *a, const void *b)
{
/* a and b point AT the array elements, which are char *.
So the real type is char *const *, not char *. */
const char *const *left = a;
const char *const *right = b;
size_t len_left = strlen(*left);
size_t len_right = strlen(*right);
if (len_left != len_right) {
/* Compare, do not subtract: size_t is unsigned and would wrap. */
return len_left < len_right ? -1 : 1;
}
return strcmp(*left, *right);
}
int main(void)
{
const char *words[] = { "delta", "be", "alpha", "cat" };
size_t n = sizeof words / sizeof words[0];
/* No & before the function name: it decays to a pointer on its own. */
qsort(words, n, sizeof words[0], by_length_then_text);
for (size_t i = 0; i < n; i++) {
printf("%s ", words[i]); /* prints: be cat alpha delta */
}
putchar('\n');
return 0;
}Common Gotchas
Calling through a mismatched function pointer type is undefined behavior
casting `int (*)(int)` to `int (*)(void)` and calling it does not truncate the arguments, it breaks the call. This is why `qsort` comparators must take `const void *` and convert inside rather than being cast into place.
A null function pointer must be checked like any other
a lookup that misses returns `NULL`, and calling through it is undefined behavior. Dispatch tables with sparse indices are a common place to forget the check.