Chapter 26 of 44

Function Pointers in C

We know that variables are stored in memory, and pointers can hold their addresses.

But functions are also stored in memory. When a program runs, the machine code of every function sits at some address. So a natural question is: can a pointer hold the address of a function?

Yes! Such a pointer is called a function pointer, and it lets us decide which function to call while the program is running.

What is a Function Pointer?

A function pointer is a pointer that stores the address of a function. Using it, we can call that function, pass it to other functions, or store it in an array.

Think of your phone's speed dial: button 1 calls Mom, button 2 calls a friend. The button doesn't contain the person, only a way to reach them. Similarly, a function pointer doesn't contain the function's code, only the address where the code lives.


Declaring a Function Pointer

Consider this function:

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

A pointer that can point to add is declared like this:

int (*operation)(int, int);

Read it piece by piece:

int   (*operation)   (int, int)
 │         │             │
 │         │             └── the function takes two ints
 │         └──────────────── operation is a pointer
 └────────────────────────── the function returns an int

A simple way to write any function pointer: take the function's declaration, and replace the function name with (*pointerName).

Function:          int add(int a, int b);
Function pointer:  int (*operation)(int, int);

The Parentheses Are Essential

The brackets around *operation are not optional. Compare:

Declaration

Meaning

int (*fp)(int, int);

fp is a pointer to a function that takes two ints and returns an int

int *fp(int, int);

fp is a function that takes two ints and returns an int *

Without the parentheses, () binds more tightly than *, so you end up declaring a function that returns a pointer.


Assigning and Calling

A function's name, used without (), gives the address of the function. So both of these work:

operation = add;     // most common
operation = &add;    // same meaning, & is optional

And both of these call the function:

operation(6, 3);       // most common
(*operation)(6, 3);    // same meaning, * is optional

Be careful: operation = add(); would try to call add and store its result, which is wrong.

#include <stdio.h>

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

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

int main()
{
    int (*operation)(int, int);   // pointer to a function taking (int, int) and returning int

    operation = add;              // point to add
    printf("add      : %d\n", operation(6, 3));

    operation = &multiply;        // & is optional
    printf("multiply : %d\n", (*operation)(6, 3));   // * is optional too

    return 0;
}

Output:

add      : 9
multiply : 18

The same line of code, operation(6, 3), calls a different function depending on what the pointer currently holds. This is the core idea behind function pointers.


Passing a Function to Another Function (Callbacks)

The most important use of function pointers is passing a function as an argument. A function passed this way is called a callback, because the receiving function "calls it back" when needed.

#include <stdio.h>

int add(int a, int b)      { return a + b; }
int subtract(int a, int b) { return a - b; }
int maxOf(int a, int b)    { return (a > b) ? a : b; }

// 'op' is a callback: the caller decides which function runs
int calculate(int (*op)(int, int), int x, int y)
{
    return op(x, y);
}

int main()
{
    printf("%d\n", calculate(add, 10, 4));
    printf("%d\n", calculate(subtract, 10, 4));
    printf("%d\n", calculate(maxOf, 10, 4));

    return 0;
}

Output:

14
6
10

calculate() doesn't know or care which operation it performs. We can add new operations later without changing calculate() at all.

Example: Apply a Function to Every Array Element

#include <stdio.h>

void applyToAll(int arr[], int n, int (*change)(int))
{
    for (int i = 0; i < n; i++)
    {
        arr[i] = change(arr[i]);
    }
}

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

void printArray(const int arr[], int n)
{
    for (int i = 0; i < n; i++)
    {
        if (i > 0)
            printf(" ");
        printf("%d", arr[i]);
    }
    printf("\n");
}

int main()
{
    int nums[] = {1, 2, 3, 4, 5};

    applyToAll(nums, 5, square);
    printArray(nums, 5);

    applyToAll(nums, 5, doubleIt);
    printArray(nums, 5);

    return 0;
}

Output:

1 4 9 16 25
2 8 18 32 50

The loop is written once; the behaviour inside it is "plugged in" through the function pointer.


Array of Function Pointers

We can store several function pointers in an array and pick one using an index. This is a neat replacement for a long switch statement in menu-driven programs.

#include <stdio.h>

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 divide(int a, int b)   { return a / b; }

int main()
{
    int (*ops[4])(int, int) = {add, subtract, multiply, divide};
    const char *names[4] = {"Add", "Subtract", "Multiply", "Divide"};

    int x = 20, y = 5;

    for (int choice = 0; choice < 4; choice++)
    {
        printf("%-8s : %d\n", names[choice], ops[choice](x, y));
    }

    return 0;
}

Output:

Add      : 25
Subtract : 15
Multiply : 100
Divide   : 4

Here, int (*ops[4])(int, int) means: ops is an array of 4 pointers to functions that take (int, int) and return int. In a real menu, the user's choice would be used as the index. Just make sure the index is checked to be within range first, because calling through an out-of-range element is undefined behavior.


Sorting with qsort()

The standard library function qsort() (from <stdlib.h>) can sort an array of any type. It can do this because you give it a comparison function through a function pointer.

void qsort(void *base, size_t count, size_t size,
           int (*compare)(const void *, const void *));

Parameter

Meaning

base

Address of the first element of the array

count

Number of elements

size

Size of each element in bytes

compare

Your comparison function

The comparison function receives the addresses of two elements as const void * (we saw void and const pointers in the previous topic) and must return:

  • a negative number if the first element should come before the second

  • zero if they are equal

  • a positive number if the first element should come after the second

#include <stdio.h>
#include <stdlib.h>

int ascending(const void *a, const void *b)
{
    int x = *(const int *)a;
    int y = *(const int *)b;

    return (x > y) - (x < y);   // -1, 0 or 1
}

int descending(const void *a, const void *b)
{
    return ascending(b, a);     // just swap the arguments
}

void printArray(const int arr[], int n)
{
    for (int i = 0; i < n; i++)
    {
        if (i > 0)
            printf(" ");
        printf("%d", arr[i]);
    }
    printf("\n");
}

int main()
{
    int marks[] = {72, 45, 90, 61, 88, 45};
    int n = sizeof(marks) / sizeof(marks[0]);

    qsort(marks, n, sizeof(int), ascending);
    printArray(marks, n);

    qsort(marks, n, sizeof(int), descending);
    printArray(marks, n);

    return 0;
}

Output:

45 45 61 72 88 90
90 88 72 61 45 45

Why Not Just return x - y;?

You will often see comparators written as return x - y;. It works for small numbers, but if x is a large positive number and y is a large negative number, x - y can overflow the int range. Signed integer overflow is undefined behavior, and the sort may give wrong results.

The expression (x > y) - (x < y) never overflows. Each comparison gives 0 or 1, so the result is always -1, 0 or 1.

Things to Know About qsort()

  • Despite its name, the C standard does not require qsort() to use the quicksort algorithm, and it does not specify its time complexity. Common implementations take about O(n log n) time on average.

  • qsort() is not guaranteed to be stable: elements that compare equal may end up in any order relative to each other.

  • bsearch() (binary search, also in <stdlib.h>) uses the same style of comparison function.


Returning a Function Pointer

A function can also return a function pointer. The syntax looks scary at first:

#include <stdio.h>

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

// getOperation takes a char and returns a pointer to a function (int, int) -> int
int (*getOperation(char symbol))(int, int)
{
    if (symbol == '+')
        return add;
    if (symbol == '-')
        return subtract;
    return NULL;
}

int main()
{
    int (*op)(int, int) = getOperation('-');

    if (op != NULL)
        printf("9 - 4 = %d\n", op(9, 4));

    if (getOperation('*') == NULL)
        printf("'*' is not supported\n");

    return 0;
}

Output:

9 - 4 = 5
'*' is not supported

Read the header from the name outwards: getOperation(char symbol) is a function, * means it returns a pointer, and (int, int) with int describe the function that pointer points to.

Also notice that a function pointer can be NULL, just like any other pointer. Always check before calling: calling through a NULL function pointer is undefined behavior and usually crashes.

Making It Readable with typedef

Long function pointer types are usually given a short name using typedef, which we will study in detail in the typedef topic. As a preview:

#include <stdio.h>

typedef int (*Operation)(int, int);

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

Operation getOperation(char symbol)
{
    return (symbol == '+') ? add : subtract;
}

int main()
{
    Operation op = getOperation('+');
    printf("%d\n", op(7, 8));
    return 0;
}

Output:

15

Now Operation means "pointer to a function taking (int, int) and returning int", and the code is much easier to read.


Reading Function Pointer Declarations

Declaration

Meaning

int f(int);

Function taking int, returning int

int *f(int);

Function taking int, returning int *

int (*f)(int);

Pointer to a function taking int, returning int

int *(*f)(int);

Pointer to a function taking int, returning int *

int (*f[5])(int);

Array of 5 pointers to functions taking int, returning int

void (*f)(void);

Pointer to a function taking no arguments and returning nothing

int (*f(char))(int, int);

Function taking char, returning a pointer to a function taking (int, int) and returning int

Rule of thumb: start at the name, go right as far as you can (() means "function", [] means "array"), then go left (* means "pointer to"), and step out of each pair of parentheses as you finish it.


Where Are Function Pointers Used?

  • Callbacks: qsort(), bsearch(), and event handlers that run when a button is clicked or a key is pressed.

  • Menu-driven programs and dispatch tables: an array of function pointers instead of a long switch.

  • State machines: each state is a function, and a pointer tracks the current state.

  • Signal handling: signal() from <signal.h> takes a pointer to the function that should run when a signal arrives.

  • Plugins and drivers: operating systems use structures full of function pointers so that different devices can provide their own read and write functions.


Function Pointer vs Normal Pointer

Point

Normal (data) pointer

Function pointer

Points to

Data (a variable, array element, ...)

Code (a function)

Example

int *p = &x;

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

Using it

Dereference: *p

Call: fp(2, 3)

Pointer arithmetic (p + 1)

Allowed (within an array)

Not allowed

Can be stored in void *

Yes

Not guaranteed by standard C

That last row matters: standard C only allows void * to hold object addresses. Converting a function pointer to void * works on many systems (POSIX requires it), but it is not portable C.


Common Mistakes

  • Forgetting the parentheses: int *fp(int, int); declares a function, not a pointer.

  • Calling the function while assigning: fp = add(); is wrong; write fp = add;.

  • Mismatched types: the pointer's parameter types and return type must match the function exactly. Calling a function through a pointer of a different type is undefined behavior, even if you force it with a cast.

  • Calling an uninitialized or NULL function pointer. Initialize it, and check for NULL when it might not be set.

  • Treating comparator parameters as values. In a qsort() comparator, a and b are addresses of elements. You must cast and dereference them first: *(const int *)a.


Interview Questions

What is a callback function?

A function that is passed (as a function pointer) to another function, which then calls it at the right time. The comparator given to qsort() is a classic example.

What is the difference between int *f(int) and int (*f)(int)?

The first declares a function returning an int *. The second declares a pointer to a function returning an int.

Are fp(2, 3) and (*fp)(2, 3) the same?

Yes. Both call the function that fp points to. Similarly, fp = add and fp = &add are the same.

Can we do arithmetic on function pointers?

No. Expressions like fp + 1 are not allowed in standard C. Only pointers to objects support pointer arithmetic. (GCC accepts it as an extension, just like arithmetic on void *, and only warns with -Wpointer-arith or -pedantic. The result is meaningless, so never rely on it.)

How does qsort() sort any data type?

It treats the array as raw bytes using void * and the element size, and it decides the order only by calling the comparison function you pass through a function pointer.

Is qsort() stable? What is its complexity?

It is not guaranteed to be stable. The standard does not specify its algorithm or complexity, but common implementations run in about O(n log n) time on average.

In Simple Words

A function pointer stores the address of a function, so we can choose which function to call while the program runs.

int (*fp)(int, int);        → declare
fp = add;                   → assign (no brackets after add)
fp(2, 3);                   → call
calculate(add, 2, 3);       → pass as a callback
int (*ops[4])(int, int);    → array of function pointers

Function pointers make C code flexible: write the general logic once and plug in the specific behaviour. Next, we'll learn how to request memory while the program runs using Dynamic Memory Allocation.