A comparison function is a caller-supplied function that tells a generic algorithm how two elements are ordered. The C library passes it to qsort or bsearch through a function pointer, allowing the same interface to operate on integers, floating-point values, strings, or application-defined objects. section 11.4
typedef int compare_function(void const*, void const*);
void* bsearch(void const* key, void const* base,
size_t n, size_t size,
compare_function* compar);
void qsort(void* base,
size_t n, size_t size,
compare_function* compar);
The interface combines void pointers for untyped array elements with element size, element count, and a comparison-function pointer. section 11.4 section 18.1.6
A safe unsigned comparison
int compare_unsigned(void const* a, void const* b){ unsigned const* A = a; unsigned const* B = b; if (*A < *B) return -1; else if (*A > *B) return +1; else return 0; } The arguments point to the two elements. A negative result means that the first precedes the second, zero means equality, and a positive result means that the first follows the second. section 11.4
A valid comparison function must preserve the contract expected by the generic algorithm:
- Interpret both void pointers as pointers to the same element type, preserving the target qualification. section 18.1.6
- Return any strictly negative value, zero, or any strictly positive value; the exact nonzero value is unimportant. section 11.4
- Avoid returning *A - *B for integers, because the subtraction can overflow even when the ordering is obvious. section 11.4
- Keep the array's element size and comparison interpretation consistent; bsearch additionally requires an array already sorted by the same ordering. section 11.4


