C/C++ Arena

Calling through a function pointer

op holds the address of a function. The first call through it runs add; after op = mul; the very same line style runs mul instead.

Watch the stack: the frame that appears is whichever function op currently holds. This is how callbacks and qsort's comparison function work.

#include <stdio.h>

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

int main(void) {
    int (*op)(int, int) = add;
    int r1 = op(3, 4);
    op = mul;
    int r2 = op(3, 4);
    printf("%d %d\n", r1, r2);
    return 0;
}

Output:

7 12

From the lesson: Function pointers and callbacks