0Pricing
C++ Academy · Lesson

Function Pointers

Pass functions as arguments.

What Is a Function Pointer?

A function pointer stores the address of a function so you can call it indirectly or pass it around like data.

  • The type encodes the signature.
  • It lets functions take behavior as a parameter.
#include <iostream>

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

int main() {
    int (*op)(int, int) = add;
    std::cout << op(3, 4) << '\n';
    return 0;
}

Declaring the Type

The declaration int (*op)(int, int) reads as: op is a pointer to a function taking two ints and returning an int. The parentheses around *op are required.

#include <iostream>

int square(int x) { return x * x; }

int main() {
    int (*fn)(int) = square;
    std::cout << fn(5) << '\n';
    return 0;
}

All lessons in this course

  1. Function Pointers
  2. std::function
  3. std::bind
  4. Choosing Callables
← Back to C++ Academy