How does the compare function in qsort work?

What a and b are is clearly stated in the documentation for qsort: these are pointers that point to array elements that have to be compared.

Comparison function in this case knows that the array elements are of type int. So it casts the void * pointers to int * type and performs a tri-state comparison of the pointed int values by subtracting the second from the first.

It will work properly for your set of values, but in general case using subtraction for tri-state comparison is a bad programming practice, since it is prone to overflow. Also, the function in your sample code unnecessarily casts away the constness of the pointed values.

A better alternative would be

int cmpfunc(const void *a, const void *b)
{
   const int *A = a, *B = b;
   return (*A > *B) - (*A < *B);
}

Leave a Comment