Function Pointers

A pointer can hold a function. Pass one to another function to choose behaviour at run time.

C · beginner · 7 min · 13 steps · free

What you'll learn

function_pointers.c

#include <stdio.h>

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);
}

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

Step by step

  1. choice holds the function add.
  2. C calls apply(), with op = → add(), x = 3 and y = 4. It gets its own variables on the stack.
  3. op(x, y) calls whichever function was passed in: add.
  4. add() has finished, so its variables are gone.
  5. apply() has finished, so its variables are gone. The value it returned, 7, is stored in r1.
  6. Now choice holds mul.
  7. C calls apply(), with op = → mul(), x = 3 and y = 4. It gets its own variables on the stack.
  8. C calls mul(), with a = 3 and b = 4. It gets its own variables on the stack.
  9. mul() has finished, so its variables are gone.
  10. apply() has finished, so its variables are gone. The value it returned, 12, is stored in r2.
  11. It prints 7 12.
  12. The method returns 0.
  13. 7 12: the same apply, two behaviours.

Common mistakes

Best practices

Key takeaways

Check yourself

Which declares a pointer to a function taking int, returning int?

Answer: int (*f)(int). Without parentheses it is a function returning int*.

qsort's comparison argument is?

Answer: A function pointer. You pass the compare function.

·

More in Pointers