liveBook · Manning

Comparison function

As explained in Modern C

A comparison function is a callback that determines the ordering of two values by returning a negative, zero, or positive result.

A comparison function is a callback that establishes an ordering between two elements. It returns a negative value when the first is smaller, zero when they compare equal, and a positive value otherwise. section 11.4

A safe unsigned comparison

The comparator receives two void pointers, converts them to unsigned pointers, and compares the pointed-to values with explicit relational tests. Returning *A - *B is unsafe for integers because the difference can overflow.

Use the callback with generic array algorithms by preserving the element type and ordering assumptions:

  • Pass the array address as a void pointer, together with the element count and element size. section 11.4
  • Give bsearch a comparator consistent with the ordering already used to sort the array. section 11.4

How Modern C covers it

How deep it goes
Explains the return contract, void-pointer conversions, and integer-overflow pitfall, but defers a complete search or sorting implementation.
Examples
Uses unsigned comparison code, an overflowing integer subtraction comparator, and qsort/bsearch declarations.
What you can do after
Apply it via qsort and bsearch by writing a consistent comparator and supplying the correct element size.
How it connects
Connects function pointers, void pointers, qsort, bsearch, arrays, and type conversions.

Also explained in

Compare how 3 books explain comparison function →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C. The section links point to the parts of the book it draws on.