← Advanced C (Pre-Kernel)C PROGRAMMING 1.7.A

Function Pointers

Declaration, assignment, calling through a pointer, typedef’d function types, arrays of function pointers, callback patterns.

StatusCollected
NotesChapter test: 4/5 (80%)

Six pieces on treating a function itself as a value — something that can be stored in a variable, passed around, and called indirectly.

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

int (*fp)(int, int) = add;   /* fp points to add */
int result = fp(3, 4);        /* calls add through the pointer — result is 7 */

The declaration syntax is the ugly part — int (*fp)(int, int) reads as "fp is a pointer to a function taking two ints and returning int." The parens around *fp matter; without them it would declare a function returning int *, a completely different thing.

Cleaning it up with typedef

typedef int (*BinOp)(int, int);

BinOp fp = add;
int result = fp(3, 4);

Callback patterns

void for_each(int *arr, int n, void (*callback)(int)) {
    for (int i = 0; i < n; i++) {
        callback(arr[i]);
    }
}

void print_int(int x) { printf("%d\n", x); }

for_each(arr, 5, print_int);   /* the loop calls whatever function was passed in */

This is the whole pattern behind a callback API — for_each doesn't know or care what print_int does, it just calls whatever function pointer it was handed. It's exactly how the kernel calls into a specific driver's .read() without needing a giant switch statement over every driver that exists.

Notes from readers

Comments — via GitHub