Lesson 201 +10 XP

Function Pointers

Function Pointers

Like data, a function lives at an address. A function pointer stores that address, so you can pass a function into another function and call it later.

Declare one

#include <iostream>

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

int (*f)(int, int) = add;   // f points to the add function

Read int (f)(int, int) from the inside out: (f) is "f is a pointer", int (int, int) is "to a function that takes two ints and returns an int". Without the parentheses, int *f(int, int) would declare a function returning a pointer instead.

Call through the pointer

std::cout << f(3, 4);   // 7

You may also write (*f)(3, 4), but plain f(3, 4) reads better.

Reassign the pointer

int mul(int a, int b) { return a * b; }
f = mul;
std::cout << f(3, 4);   // 12

A function pointer must keep a matching signature.

Function pointers as callbacks

The classic use is callbacks: hand a generic function the specific operation.

int apply(int a, int b, int (*op)(int, int)) {
    return op(a, b);
}

std::cout << apply(3, 4, add);   // 7
std::cout << apply(3, 4, mul);   // 12

Because the pointer is a value, the same apply behaves differently on each call.

TL;DR

  • A function pointer stores a function's address: int (*f)(int, int).
  • Declare with (*name) and the signature; call with f(a, b).
  • Reassign it to any function with a matching signature.
  • Use them to pass behavior as a callback argument.
  • Since C++11, lambdas offer a friendlier alternative for most cases.