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

Common pitfalls in comparison function logic

Common pitfalls in comparison function logic

What you'll learn: How to avoid logical errors when writing comparison functions for qsort and bsearch that lead to unstable programs and memory corruption.

The qsort function is a powerful tool, but it is only as smart as the comparison function you provide. Think of the comparison function like a scale: it must be consistent. If you tell the computer that "A is heavier than B" and "B is heavier than A" at the same time, the sorting algorithm will get confused, potentially leading to infinite loops or crashes.

The Transitivity Trap

The most common mistake is failing to handle every possible outcome. Your function must return an integer that is less than, equal to, or greater than zero. A frequent pitfall is using simple subtraction for comparison, like return a - b;.

While this seems clever, it can lead to integer overflow. If a is a very large positive number and b is a very large negative number, a - b might exceed the limits of a signed integer, wrap around to a negative value, and tell qsort that the larger number is actually smaller.

The Floating-Point Fumble

When comparing float or double values, never use subtraction. Because qsort expects an int, returning 0.5 will be truncated to 0, telling the algorithm the numbers are equal when they aren't. Always use explicit if statements.

The Strict Weak Ordering Rule

To keep the "scale" balanced, your logic must follow Strict Weak Ordering. This means if A == B, then B == A. If A < B and B < C, then A must be < C. If your logic is "fuzzy"—for example, saying numbers are equal if they are "close enough"—the algorithm might never finish.

A Robust Implementation

Here is how to safely compare two integers without risk of overflow:

#include <stdlib.h>

int compare_ints(const void *a, const void *b) {
    // Cast the void pointers to the actual data type
    int arg1 = *(const int*)a;
    int arg2 = *(const int*)b;

    // Use explicit comparisons instead of subtraction
    if (arg1 < arg2) return -1;
    if (arg1 > arg2) return 1;
    
    // They are equal
    return 0;
}

By explicitly returning -1, 1, or 0, you ensure your logic is crystal clear to the C Standard Library, preventing the "logical vertigo" that causes sorting bugs.

Key takeaway

Always use explicit if statements rather than subtraction in comparison functions to avoid integer overflow and truncation errors.