Reading history

Function Pointers in C with Examples

6 min read 5 views

Learn C function pointers: syntax, calling through a pointer, arrays of function pointers, callbacks with qsort, and typedef to keep them readable.

Once a program is running, each of its functions sits somewhere in memory and has an address, the same as any variable. A function pointer stores that address, so you can decide which function to call while the program runs. This is how C does callbacks, plug-in style menus and the custom sorting that qsort offers.

In this lesson you will learn

  • What a function pointer holds and how to read its declaration
  • How to assign and call through a function pointer
  • How to pass a function to another function as a callback
  • How to build a menu from an array of function pointers
  • How typedef makes the syntax readable

What a Function Pointer Stores

When you write the name of a function without brackets, such as add, C treats it as the function’s address. A function pointer is a variable that can hold such an address, as long as the function has the right signature: the same return type and parameter types.

Normal pointers are covered in Pointers in C. Function pointers follow the same idea, but you call through them instead of reading data.

Declaring and Calling Function Pointers

int (*op)(int, int);

Read it from the name outwards: op is a pointer (*op) to a function that takes (int, int) and returns int. The brackets around *op matter. Without them, int *op(int, int); declares a function that returns an int *.

#include <stdio.h>

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

int main(void) {
    int (*op)(int, int);          /* op points to a function taking two ints, returning int */
    op = add;
    printf("op(6, 7) with add      = %d\n", op(6, 7));
    op = multiply;
    printf("op(6, 7) with multiply = %d\n", op(6, 7));
    printf("same address? %s\n", (op == &multiply) ? "yes" : "no");
    return 0;
}

Output

op(6, 7) with add      = 13
op(6, 7) with multiply = 42
same address? yes
  • op = add; and op = &add; mean the same thing.
  • op(6, 7) and (*op)(6, 7) also mean the same thing. The first is more common today.
  • The same line, op(6, 7), calls a different function depending on what op currently holds.

Callbacks and Menus With Function Pointers

Callbacks: Letting qsort Call Your Code

A callback is a function you hand to another function so it can call you back. The standard library’s qsort can sort any kind of data, but it does not know how to compare your items. You give it a comparison function, and qsort calls it whenever it needs to compare two items.

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

typedef struct { char name[12]; int marks; } Student;

static int by_marks_desc(const void *a, const void *b) {
    const Student *x = a, *y = b;
    return (y->marks > x->marks) - (y->marks < x->marks);   /* no overflow, unlike y - x */
}

static int by_name(const void *a, const void *b) {
    const Student *x = a, *y = b;
    return strcmp(x->name, y->name);
}

static void show(const char *title, const Student s[], int n) {
    printf("%s:", title);
    for (int i = 0; i < n; i++) printf(" %s(%d)", s[i].name, s[i].marks);
    printf("\n");
}

int main(void) {
    Student s[] = {{"Nadia", 81}, {"Arif", 92}, {"Tania", 95}, {"Imran", 88}};
    qsort(s, 4, sizeof s[0], by_marks_desc);   /* qsort calls our function back */
    show("by marks", s, 4);
    qsort(s, 4, sizeof s[0], by_name);
    show("by name ", s, 4);
    return 0;
}

Output

by marks: Tania(95) Arif(92) Imran(88) Nadia(81)
by name : Arif(92) Imran(88) Nadia(81) Tania(95)

The same qsort call sorts in two different orders, because the comparison function changes. The comparison function must return a negative number if the first item should come first, zero if they are equal, and a positive number otherwise. It receives const void * pointers, which you convert to your real type.

The expression (y > x) - (y < x) produces -1, 0 or 1. It avoids the overflow that the shortcut y - x can cause with very large or very negative numbers.

Storing function pointers in an array replaces long switch statements. The user’s choice becomes an index, and the array says which function runs.

#include <stdio.h>

typedef double (*Convert)(double);       /* a name for "pointer to double f(double)" */

static double km_to_miles(double km)  { return km * 0.621371; }
static double kg_to_pounds(double kg) { return kg * 2.204623; }
static double c_to_f(double c)        { return c * 9.0 / 5.0 + 32.0; }

int main(void) {
    const char *label[] = {"km -> miles", "kg -> pounds", "C -> F"};
    Convert menu[] = {km_to_miles, kg_to_pounds, c_to_f};   /* a table of functions */
    double input = 10.0;
    for (int choice = 0; choice < 3; choice++)
        printf("%d. %-13s %.2f -> %.2f\n", choice + 1, label[choice], input, menu[choice](input));
    return 0;
}

Output

1. km -> miles   10.00 -> 6.21
2. kg -> pounds  10.00 -> 22.05
3. C -> F        10.00 -> 50.00

typedef double (*Convert)(double); creates a short name for the pointer type, so the array declaration reads simply as Convert menu[]. Adding a new conversion only means writing one function and adding it to the table.

Signature Mismatches and Messy Syntax

  1. Forgetting the brackets. int *f(int); is a function returning a pointer; int (*f)(int); is a pointer to a function.
  2. Mismatched signatures. Assigning a function with different parameter types and forcing it with a cast compiles, but calling it is undefined behaviour. Make the types match.
  3. Calling a NULL pointer. An uninitialised or NULL function pointer crashes when called. Check it first: if (handler) handler(event);
  4. Unreadable declarations. Something like void (*signal(int, void (*)(int)))(int); is hard to read. Use typedef to name the pointer type.
  5. Wrong qsort comparator. Returning only 0 or 1, or comparing by subtraction with values that can overflow, gives wrong orderings.

Practice Exercises

Exercise 1. Declare a pointer check to a function that takes a const char * and returns bool.

Show answer
bool (*check)(const char *);

Exercise 2. Write a qsort comparison function that sorts ints from smallest to largest.

Show answer
int ascending(const void *a, const void *b) {
    int x = *(const int *)a, y = *(const int *)b;
    return (x > y) - (x < y);
}

Exercise 3. Write a function apply that takes an array, its length and a function pointer, and replaces each element with the function’s result.

Show answer
void apply(int a[], int n, int (*f)(int)) {
    for (int i = 0; i < n; i++)
        a[i] = f(a[i]);
}

Frequently Asked Questions

Where are function pointers used in real programs?

In sorting and searching (qsort, bsearch), event and signal handlers, plug-in systems, device driver tables and state machines.

Can a function pointer point to a function with different parameters?

Not safely. The pointer’s type must match the function’s signature exactly, or the call is undefined behaviour.

Can I do arithmetic on function pointers?

No. Unlike data pointers, function pointers cannot be incremented or subtracted. You can only assign, compare and call them.

Function Pointers: Key Points

  • A function pointer stores a function’s address and must match its signature.
  • Declare with brackets: return_type (*name)(parameter types).
  • Call it like the function itself: name(args).
  • Callbacks such as qsort‘s comparison function let library code run your code.
  • Use typedef and arrays of function pointers for clean menus and dispatch tables.
Lessons are also marked complete when you click Next.