Skip to content
systemcoding.dev
Fundamentals

Write a qsort comparator that cannot overflow: (a > b) - (a < b)

Write a qsort comparator that cannot overflow with (a > b) - (a < b), which returns -1, 0 or 1 for any int pair and is safe for INT_MIN and INT_MAX.

2 min read
Summarize in AI

The tempting comparator for integers is return a - b;. It works on small numbers and fails silently on large ones, because the subtraction overflows and the sign comes out wrong, which is undefined behaviour for int. Comparing twice and subtracting the two booleans gives -1, 0 or 1 with no arithmetic on the values.

cmp.cc
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

static int cmp_int(const void *pa, const void *pb)
{
    int a = *(const int *)pa;
    int b = *(const int *)pb;

    return (a > b) - (a < b);
}

int main(void)
{
    int v[] = {5, INT_MIN, 2, INT_MAX, -7};

    qsort(v, 5, sizeof v[0], cmp_int);
    for (int i = 0; i < 5; i++)
        printf("%d ", v[i]);
    putchar('\n');
    return 0;
}
Text
-2147483648 -7 2 5 2147483647

A relational expression in C yields 1 or 0, so (a > b) - (a < b) is 1 when a is larger, -1 when it is smaller and 0 when equal. The compiler turns it into a compare and two flag reads, not into branches, on common targets. With a - b, comparing INT_MIN and 5 would compute a number below the minimum, and qsort could place the elements in the wrong order or, with some implementations, misbehave.

The same pattern works for long long, size_t and floating-point keys, though NaN needs its own rule because every comparison with it is false. Describe the comparator's contract in the C standard's terms: it must be consistent, or qsort has undefined behaviour.

Taggedc
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.