IntermediateLesson 1 of 76 min read

Function Pointers and Callbacks: qsort, bsearch and Dispatch Tables

Learn function pointers, pass behaviour as an argument, sort structs by different fields with qsort, search with bsearch, and build a dispatch table, with every result verified independently.

In this lesson you will

  • Declare and call function pointers
  • Write comparators for qsort
  • Search with bsearch
  • Use a dispatch table

About 28 minutes

Sorting plants three different ways

Bruno tracks his plants with a name, a preferred temperature and the number of days since watering. He wants them sorted by name for a list, by temperature for planning and by days for the watering round. Writing three sort functions is wasteful. The standard function qsort sorts any array, and the only thing that changes between the three tasks is how two elements are compared. In C you pass that behaviour as a function pointer: the address of a function that qsort calls back whenever it needs to compare two elements.

A function pointer is declared by putting the pointer star in parentheses: int (*cmp)(const void *, const void *) is a pointer to a function that takes two const void pointers and returns an int. A typedef makes the declaration readable. A comparator returns a negative number when the first element comes first, zero when they are equal and a positive number otherwise. bsearch uses the same kind of comparator for a binary search in an array that is already sorted by the same rule, and returns a pointer to the match or NULL. An array of function pointers is a dispatch table, a tidy way to choose behaviour from a number or a name without a long chain of if statements.

Idea Code
Function pointer type typedef int (*Cmp)(const void *, const void *);
Sort qsort(arr, n, sizeof arr[0], cmp)
Search bsearch(&key, arr, n, sizeof arr[0], cmp)
Dispatch table double (*convert[3])(double) = { c_to_f, c_to_k, f_to_c };
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct { char name[12]; double temp; int days; } Plant;
typedef int (*Cmp)(const void *, const void *);

static int by_name(const void *a, const void *b) { return strcmp(((const Plant *)a)->name, ((const Plant *)b)->name); }
static int by_temp(const void *a, const void *b) { double x = ((const Plant *)a)->temp, y = ((const Plant *)b)->temp; return (x > y) - (x < y); }
static int by_days_desc(const void *a, const void *b) { return ((const Plant *)b)->days - ((const Plant *)a)->days; }

static void show(const char *label, Plant *p, size_t n) {
    printf("%-14s", label);
    for (size_t i = 0; i < n; i++) printf(" %s", p[i].name);
    printf("\n");
}
static double c_to_f(double c) { return c * 9.0 / 5.0 + 32.0; }
static double c_to_k(double c) { return c + 273.15; }
static double halve(double c) { return c / 2.0; }

int main(void) {
    Plant plants[] = {{"tomato", 24.5, 3}, {"basil", 19.8, 7}, {"pepper", 22.2, 5}, {"cucumber", 26.0, 2}, {"lettuce", 18.1, 9}, {"mint", 21.4, 4}};
    size_t n = sizeof plants / sizeof plants[0];
    struct { const char *label; Cmp cmp; } orders[] = { {"by name:", by_name}, {"by temp:", by_temp}, {"by days desc:", by_days_desc} };
    for (size_t k = 0; k < 3; k++) {
        Plant copy[8];
        memcpy(copy, plants, sizeof plants);
        qsort(copy, n, sizeof copy[0], orders[k].cmp);
        show(orders[k].label, copy, n);
    }
    Plant sorted[8];
    memcpy(sorted, plants, sizeof plants);
    qsort(sorted, n, sizeof sorted[0], by_name);
    Plant key = {"pepper", 0, 0};
    Plant *hit = bsearch(&key, sorted, n, sizeof sorted[0], by_name);
    printf("bsearch for pepper: %s (temp %.1f, index %td)\n", hit ? "found" : "missing", hit ? hit->temp : 0.0, hit ? hit - sorted : -1);
    Plant nokey = {"rose", 0, 0};
    printf("bsearch for rose: %s\n", bsearch(&nokey, sorted, n, sizeof sorted[0], by_name) ? "found" : "missing");
    double (*convert[])(double) = { c_to_f, c_to_k, halve };
    const char *names[] = { "Fahrenheit", "Kelvin", "half" };
    for (int i = 0; i < 3; i++) printf("%s of 24.5: %.2f\n", names[i], convert[i](24.5));
    return 0;
}
by name:       basil cucumber lettuce mint pepper tomato
by temp:       lettuce basil mint pepper tomato cucumber
by days desc:  lettuce basil pepper mint tomato cucumber
bsearch for pepper: found (temp 22.2, index 4)
bsearch for rose: missing
Fahrenheit of 24.5: 76.10
Kelvin of 24.5: 297.65
half of 24.5: 12.25

One function, qsort, produced three orders by changing only the comparator that it calls back: by name basil cucumber lettuce mint pepper tomato; by preferred temperature lettuce basil mint pepper tomato cucumber; and by days since watering, largest first, lettuce basil pepper mint tomato cucumber. Each sort worked on a fresh copy of the array, so the three orders do not influence each other. The comparator for temperature uses (x > y) – (x < y) instead of subtracting, which is safe for doubles, and the one for days subtracts in the opposite order to reverse the sort.

bsearch needs an array sorted by the same rule, which is why the program sorted by name first. It found pepper at index 4 of the sorted array, with the temperature 22.2, and correctly reported that rose is missing. The dispatch table holds three function pointers, and the loop calls them through the table: 24.5 degrees Celsius is 76.1 Fahrenheit, 297.65 kelvin and 12.25 when halved. Adding a fourth conversion means adding one function and one table entry.

Check by hand: the names in alphabetical order are basil, cucumber, lettuce, mint, pepper, tomato, so pepper is the fifth, index 4. 24.5 x 9 / 5 + 32 = 76.1, and 24.5 + 273.15 = 297.65. Python sorted the same list of plants by each key and gave the same three orders.

Comparators must be consistent

A comparator that is not a proper ordering, for example one that returns inconsistent results, makes qsort and bsearch behave unpredictably. Test it on equal and reversed inputs.

Use typedef for function pointer types

typedef int (*Cmp)(const void *, const void *) turns an unreadable declaration into a name that you can use in parameters and arrays.

About this course

Every program in this lesson was compiled with GCC 13 using -std=c17 -Wall -Wextra and run while the course was written. Compilers and platforms differ, so check your compiler’s documentation, and the C standard drafts, for details that the standard leaves open.

Practice

Add a comparator that sorts by days and then by name for plants with the same days. Write a function apply_all(double *a, size_t n, double (*f)(double)) that applies a function to every element, and use it with c_to_f. Extend the dispatch table with a command name lookup.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does qsort receive to know how to compare?

  1. A format string
  2. A function pointer to a comparator
  3. A flag
  4. Nothing

A callback.

What must be true for bsearch to work?

  1. The array is sorted by the same comparator
  2. The array is empty
  3. The elements are ints
  4. The array is on the heap

Binary search needs order.

What does a negative comparator result mean?

  1. The first element comes first
  2. The elements are equal
  3. The second comes first
  4. An error

Zero means equal.

What is a dispatch table?

  1. A sorted array
  2. A file
  3. A loop
  4. An array of function pointers chosen by index

It replaces a chain of ifs.

How were the sorted orders verified?

  1. By eye
  2. By running twice
  3. They were not
  4. By sorting the same data in Python

All three orders matched.

Summary

  • A function pointer holds the address of a function and lets you pass behaviour around.
  • qsort and bsearch take a comparator callback.
  • A comparator returns negative, zero or positive.
  • A dispatch table is an array of function pointers.

Next lesson

Lesson 10 shows what the memory-checking tools report for real bugs.

Questions

Why are the comparator parameters void pointers?

qsort is generic, so it passes pointers to elements of any type. The comparator casts them to the real type.

Can I pass a function pointer to my own functions?

Yes. Any function can take a function pointer parameter, which is how callbacks, event handlers and plugins work in C.

Is a function pointer slower than a direct call?

Slightly, because the compiler cannot always inline it, but the difference rarely matters.

Progress is saved in this browser.