CC Explainer
C · 2 · Memory & Pointers9 / 35 · 26%

Function Pointers

Functions have addresses too — pass them around like data.

shortcuts: ← prev · → next · M mark
1

Declare

int (*fp)(int, int) — parentheses around *fp are required.

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

int (*fp)(int, int) = add;
printf("%d\n", fp(2, 3));  // 5
2

Callbacks

Function pointers make qsort, atexit, event loops possible.

Example
example
int cmp(const void *a, const void *b) {
    return *(int*)a - *(int*)b;
}

int v[] = {3, 1, 4, 1, 5};
qsort(v, 5, sizeof(int), cmp);
3

typedef for Sanity

The syntax is ugly. typedef makes it usable.

Example
example
typedef int (*BinaryOp)(int, int);

BinaryOp op = add;
printf("%d\n", op(4, 5));