AnyCompiler

Function Pointers

A function, like a variable, lives at an address — and C lets you store that address in a pointer. int (*operation)(int, int) declares operation as a pointer to a function taking two ints and returning an int; assigning it a function name (without calling it) stores that function's address.

#include <stdio.h>

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

int main() {
    int (*operation)(int, int) = add;
    printf("%d\n", operation(5, 3));
    operation = subtract;
    printf("%d\n", operation(5, 3));
    return 0;
}
Output
8
2

Calling operation(5, 3) calls whichever function operation currently points to — add the first time, subtract after reassignment. This is how C implements callbacks and dynamic dispatch without any of the class or interface machinery other languages on this site use for the same idea.

Next: the preprocessor — a separate, purely textual pass that runs before the compiler ever sees your code.

Practice exercise

Write functions add(int,int) and subtract(int,int). Declare a function pointer initialized to add, call it with (5, 3) and print the result.