Lesson 15 / 38

Function Pointers & Callbacks

Store and pass functions with function pointers to write callbacks and flexible code like qsort comparators.

Declaring a function pointer

A function pointer stores the address of a function. The declaration repeats the function's return type and parameter types.

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

int apply(int (*op)(int, int), int x, int y) {
    return op(x, y);   // call through the pointer
}

int main(void) {
    printf("%d %d\n", apply(add, 3, 4), apply(mul, 3, 4));   // 7 12
    return 0;
}

Callbacks with qsort

The standard qsort takes a comparison function, so one routine sorts any type.

#include <stdlib.h>

int cmp_int(const void *a, const void *b) {
    int x = *(const int *)a, y = *(const int *)b;
    return (x > y) - (x < y);
}

int nums[] = {5, 2, 9, 1};
qsort(nums, 4, sizeof(int), cmp_int);

Use a typedef to keep function pointer types readable, for example typedef int (*BinOp)(int, int);.

Quick check

Quick check: What does a function pointer store?

  • The address of a function
  • The return value of a function
  • A copy of the function body
  • The number of arguments
Answer

The address of a function — You call the function through that address.