9.1 Defining the Comparison Function

In order to use the sorted array library functions, you have to describe how to compare the elements of the array.

To do this, you supply a comparison function to compare two elements of the array. The library will call this function, passing as arguments pointers to two array elements to be compared. Your comparison function should return a value the way strcmp (see String/Array Comparison) does: negative if the first argument is “less” than the second, zero if they are “equal”, and positive if the first argument is “greater”.

Here is an example of a comparison function which works with an array of numbers of type long int:

int
compare_long_ints (const void *a, const void *b)
{
  const long int *la = a;
  const long int *lb = b;

  return (*la > *lb) - (*la < *lb);
}

(The code would have to be more complicated for an array of double, to handle NaNs correctly.)

The header file stdlib.h defines a name for the data type of comparison functions. This type is a GNU extension.

int comparison_fn_t (const void *, const void *);