Course contentsShow
← C
Lesson 877 of 1,21912. The Standard LibraryFree lesson

Writing an integer comparison function

Writing an integer comparison function

What you'll learn: How to create a specific helper function that tells the standard C library how to order two whole numbers.

The "Sorting Brain" analogy

Imagine you hire a professional organizer to arrange your library. The organizer knows how to move books around efficiently, but they don't know your specific preference: should they be sorted by height, color, or title? To get the job done, you must provide the organizer with a simple rule they can apply to any two books they pick up.

In C, the qsort() function is your professional organizer. It handles the complex logic of sorting, but it requires you to provide a comparison function. This function acts as the rulebook, telling C which of two numbers is "smaller" or "larger."

The Return Value Contract

To work with the standard library, your comparison function must follow a strict three-way contract based on its return value:

  1. Negative result: The first number belongs before the second.
  2. Zero: The two numbers are equal.
  3. Positive result: The first number belongs after the second.

The Boilerplate Code

Because qsort() is designed to handle any data type (from integers to complex structures), it uses "void pointers" (void *). These are generic pointers that can point to anything. To compare integers, we must first tell C to treat these generic pointers as integer pointers.

int compare_ints(const void *a, const void *b) {
    // 1. Convert the generic pointers to integer pointers
    // 2. Dereference them to get the actual values
    int val1 = *(int *)a;
    int val2 = *(int *)b;

    // 3. Apply the logic
    if (val1 < val2) return -1; // val1 comes first
    if (val1 > val2) return 1;  // val1 comes second
    return 0;                   // they are equal
}

The "Subtract Trick"

You will often see a shortcut for this logic: return (val1 - val2);. If val1 is 5 and val2 is 10, the result is -5 (negative), placing 5 first. While elegant, be careful—if the numbers are extremely large or small, subtracting them can cause an "overflow" error. For beginners, using explicit if statements is the safest way to ensure your comparison function is robust and easy to read.

Key takeaway

A comparison function must return a negative, zero, or positive integer to define the relative order of two elements.