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

The `qsort` callback mechanism

The qsort callback mechanism

What you'll learn: How to pass a function as an argument to let C's built-in sorting tool handle any type of data.

The "Chef" and the "Taste Tester"

Imagine you have a professional chef who knows exactly how to organize a massive buffet, but they have no idea what "tasty" means to you. The chef can move the plates around perfectly, but they need you to stand nearby and point at two dishes to say which one should come first.

In C, the qsort (quick sort) function is that chef. It is a powerful, generic tool that can sort any array—integers, strings, or even custom structures. However, because it is generic, it doesn't know the rules for your specific data. To bridge this gap, qsort uses a function pointer as a "callback."

How the callback works

When you call qsort, you pass it the address of a comparison function you wrote. As qsort runs, it "calls back" to your function whenever it needs to decide the order of two elements.

Your function must follow a strict signature. It takes two const void * pointers (which basically mean "pointers to something, I don't know what") and returns an integer:

  • Negative: If the first element should come before the second.
  • Zero: If they are equal.
  • Positive: If the first element should come after the second.

Seeing it in action

Here is how we tell qsort to sort an array of integers in ascending order:

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

// This is our callback function
int compare_ints(const void *a, const void *b) {
    // Cast the generic pointers back to integer pointers and dereference them
    int val1 = *(int*)a;
    int val2 = *(int*)b;

    return (val1 - val2);
}

int main() {
    int data[] = {42, 7, 101, -5, 22};
    int n = 5;

    // We pass 'compare_ints' (the function pointer) as the last argument
    qsort(data, n, sizeof(int), compare_ints);

    for(int i = 0; i < n; i++) {
        printf("%d ", data[i]);
    }
    return 0;
}

By changing just the logic inside compare_ints (for example, returning val2 - val1), you can flip the entire sorting order to descending without ever touching the complex sorting algorithm itself. The function pointer makes the code incredibly flexible.

Key takeaway

A callback allows a generic function like qsort to execute your custom logic by receiving the memory address of your comparison function.