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 qsort function

Synopsis

#include <stdlib.h>
void qsort(void *base, size_t nmemb, size_t size,
           int (*compar)(const void *, const void *));

Description
The qsort function sorts an array of nmemb objects, the initial element of which is pointed to by base. The size of each object is specified by size.

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 说,对于任何aba ? bb ? a。用a代替b给出a ? aa ? a。所以a ? a。那么条件满足反对称性:我们有a ? aa ? a,所以a =。)


以上是Cantheqsortcomparisonfunctionalwaysreturnanon-zerovalue?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>