Ch6.12: Function Pointers

Overview

A function pointer is a pointer that refers to a function instead of data. Function pointers allow you to:

In this chapter, you will learn how function pointers work, how to declare them, how to call them, and how to print their addresses using the ::fast_io::funcvw() manipulator.

1. Function types

A function has a type based on its parameter list and return type.


int add(int a, int b);

The type of add is:


int(int, int)

This means: “a function taking two ints and returning an int.”

2. Functions decay to pointers

Just like arrays decay to pointers, the name of a function decays to a pointer to that function.


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

int (*p)(int, int) = add; // function pointer

The type of p is “pointer to function taking two ints and returning int.”

3. Calling through a function pointer

You can call a function pointer exactly like a normal function.


int result = p(3, 4);   // calls add(3, 4)

You may also write:


int result = (*p)(3, 4); // equivalent

4. Passing function pointers to functions

A function pointer can be used as a parameter type.


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

Usage:


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

::fast_io::println(operate(3, 4, add)); // 7
::fast_io::println(operate(3, 4, mul)); // 12

5. Using using aliases for clarity

Function pointer syntax is verbose. You can simplify it with a using alias.


using binary_op = int(*)(int, int);

int operate(int a, int b, binary_op op)
{
    return op(a, b);
}

This makes code easier to read and maintain.

6. Returning function pointers

A function can return a function pointer.


binary_op choose(bool multiply)
{
    if(multiply)
        return mul;
    return add;
}

Usage:


auto f = choose(true);
::fast_io::println(f(3, 4)); // 12

7. Arrays of function pointers

You can store multiple functions in an array.


binary_op ops[2]{add, mul};

::fast_io::println(ops[0](3, 4)); // add
::fast_io::println(ops[1](3, 4)); // mul

This is useful for jump tables, interpreters, and dispatch systems.

8. Printing function addresses with ::fast_io::funcvw()

The fast_io library provides a special manipulator named funcvw() that prints the address of a function or function pointer. This is extremely useful for debugging, teaching, and verifying that two function pointers refer to the same function.

Example: printing a function’s address


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

println(funcvw(add));

This prints the address of the add function.

Example: printing a function pointer’s address


int (*p)(int, int) = add;

println(funcvw(p));

This prints the address stored in p. It should match the address printed for add.

funcvw() works for:

9. Why function pointers matter

Function pointers are essential in:

They are also the foundation for more advanced features such as:

Key takeaways