Course contentsShow
← C
Lesson 928 of 1,21913. Advanced CFree lesson

Declaring pointers to functions

Declaring pointers to functions

What you'll learn: How to store the memory address of a function in a variable so you can pass logic around your program like data.

Functions have addresses, too

Up to this point, you have used pointers to point at variables—integers, characters, or structs. But in C, the code of a function itself lives in memory at a specific address. A function pointer is simply a variable that stores that address.

Think of a standard function as a fixed house on a street. A function pointer is like a GPS coordinate written on a sticky note. You can change what is written on the note to point to a different house, allowing your program to decide which "room" to enter while it is running.

The "Inside-Out" Syntax

Declaring a function pointer is notoriously tricky because of the syntax. To create one, you must match the signature (the return type and the arguments) of the function you want to point to.

If we have a function: int add(int a, int b) { return a + b; }

The pointer declaration looks like this: int (*ptr)(int, int);

Why the parentheses around *ptr? In C, operator precedence gives function calls () higher priority than pointers *. Without the parentheses, int *ptr(int, int) tells C you are declaring a function that returns a pointer to an integer. The parentheses force C to treat ptr as a pointer first.

Putting it to work

Once declared, you assign a function to the pointer by using the function's name (without parentheses).

#include <stdio.h>

int multiply(int a, int b) {
    return a * b;
}

int main() {
    // 1. Declare the pointer with matching signature
    int (*operation)(int, int);

    // 2. Point it to the multiply function
    operation = multiply;

    // 3. Call the function through the pointer
    int result = operation(10, 5);

    printf("The result is: %d", result); // Outputs 50
    return 0;
}

This becomes incredibly powerful when you want to write a function that accepts another function as an argument, such as a sorting algorithm that needs a custom "comparison" function.

Key takeaway

A function pointer is declared by wrapping the pointer name in parentheses, like ( *name ), and it must strictly match the return type and parameter list of the functions it points to.