chq*_*lie 0 c sorting qsort language-lawyer
An ascending sort callback function for qsort and bsearch on an array of int could look like this:
int ascending(const void *o1, const void *o2) {
int a = *(const int *)o1;
int b = *(const int *)o2;
return a < b ? -1 : 1;
}
Run Code Online (Sandbox Code Playgroud)
Yet this function seems to violate the constraint on the compar function as specified in the C Standard:
7.22.5.2 The
qsortfunctionSynopsis
Run Code Online (Sandbox Code Playgroud)#include <stdlib.h> void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));Description
Theqsortfunction sorts an array ofnmembobjects, the initial element of which is pointed to bybase. The size of each object is specified bysize.The contents of the array are sorted into ascending order according to a comparison function pointed to by
compar, which is called with two arguments that point to the objects being compared. The function shall return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.If two elements compare as equal, their order in the resulting sorted array is unspecified.
Is this comparison function OK or can it cause undefined behavior?