I found this sample code online, which explains how the qsort function works. I could not understand what the compare function returns.
#include "stdlib.h" int values[] = { 88, 56, 100, 2, 25 }; int cmpfunc (const void * a, const void * b) //what is it returning? { return ( *(int*)a - *(int*)b ); //What is a and b? } int main(int argc, _TCHAR* argv[]) { int n; printf("Before sorting the list is: \n"); for( n = 0 ; n < 5; n++ ) { printf("%d ", values[n]); } qsort(values, 5, sizeof(int), cmpfunc); printf("\nAfter sorting the list is: \n"); for( n = 0 ; n < 5; n++ ) { printf("%d ", values[n]); } return 0; }
values. The function returns the value ofa-b, which will be< 0(a negative number) ifais smaller,0if they're equal, or> 0(a positive number) if a is larger.-1or1:strcmp()(or the comparison function passed toqsort()) is allowed to return any negative or positive values for those cases.int, hence the behaviour is undefined. What is worse, the usual behaviour of generated code is to wrap this to a positive number 1294967296, which completely breaks the sort. See AnT's answer for the one that works correctly and this QA for what can happen if you use this comparison function