Cantheqsortcomparisonfunctionalwaysreturnanon-zerovalue?
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;
}
Yet this function seems to violate the constraint on the compar function as specified in the C Standard:
7.22.5.2 The
qsortfunctionSynopsis
#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?
回答
C 2018 7.22.5 4 说:
当相同的对象(由 size 字节组成,不管它们在数组中的当前位置)被多次传递给比较函数时,结果应彼此一致。也就是说,因为
qsort它们应该在数组上定义一个总排序,并且对于bsearch同一个对象应该总是以相同的方式与键进行比较。
甲总订单需要一个=一个。(要从维基百科页面的定义中看到这一点:Connexity 说,对于任何a和b,a ? b或b ? a。用a代替b给出a ? a或a ? a。所以a ? a。那么条件满足反对称性:我们有a ? a和a ? a,所以a =一。)