Course contentsShow
← C
Lesson 517 of 1,2197. PointersFree lesson

Arrays of function pointers

Arrays of function pointers

What you'll learn: How to store multiple functions in a single list to build flexible menu systems or command handlers.

The "Remote Control" analogy

Imagine you have a universal remote control. Instead of having ten different remotes for ten different devices, you have one device with a row of buttons. Each button is assigned to a specific action: button [0] turns on the TV, button [1] starts the DVD player, and button [2] dims the lights.

In C, an array of function pointers is that row of buttons. It is a list where every element is a "pointer" (an address) to a function rather than a piece of data like an integer. This allows you to call different functions by simply changing an index number, rather than writing a long, messy chain of if-else or switch statements.

Defining the array

To create this array, all functions must have the same "signature"—meaning they must return the same type and accept the same parameters.

Here is how you bundle three simple math operations into a single array:

#include <stdio.h>

// Functions must have the same signature (int return, two int params)
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int multiply(int a, int b) { return a * b; }

int main() {
    // Define an array of 3 function pointers
    // Syntax: return_type (*array_name[size])(parameters)
    int (*operations[3])(int, int) = {add, subtract, multiply};

    int x = 10, y = 5;

    // Use a loop or an index to call the functions
    for (int i = 0; i < 3; i++) {
        int result = operations[i](x, y);
        printf("Operation %d result: %d\n", i, result);
    }

    return 0;
}

Why use this?

The real power here is decoupling. Without an array, if you wanted to add a "Divide" feature, you would have to add a new case to a switch statement deep in your logic. With a function pointer array, you simply write the new function and add its name to the list.

This technique is the backbone of "jump tables" in low-level programming and is frequently used to handle user input in games, where input_handlers[key_code]() triggers the correct action instantly.

Key takeaway

An array of function pointers lets you map numbers to actions, replacing complex conditional logic with a clean, indexable list of functions.