I see lots of people use subtraction in a qsort comparator function. I think it is wrong because when dealing with these numbers: int nums[]={-2147483648,1,2,3}; INT_MIN = -2147483648;
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
I wrote this function to test:
#include <stdio.h>
#include <limits.h>
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main(void)
{
int a = 1;
int b = INT_MIN;
printf("%d %d\n", a,b);
printf("%d\n",compare((void *)&a,(void *)&b));
return 0;
}
The output is:
1 -2147483648
-2147483647
but a > b
so the output should be positive。
I have seen many books write like this. I think it is wrong; it should be written like this when dealing with int
types:
int compare (const void * a, const void * b)
{
if(*(int *)a < *(int *)b)
return -1;
else if(*(int *)a > *(int *)b)
return 1;
else
return 0;
}
I just cannot figure out why many books and web sites write in such a misleading way. If you have any different view, please let me know.
qsort()
, overflow of signal integer is undefined behavior, what did you expect ? there is aINT_MAX
too and1 + INT_MIN
overflow. – Facula1 - (-INT_MIN) == 1 + INT_MIN
– Facula1 + INT_MIN
shouldn't overflow.1 + INT_MAX
overflows.INT_MIN - 1
overflows. – BarefootINT_MIN
to-2147483648
but I keepINT_MIN
for some obscure reason – Facula