I'm confused about the result of test function, which is -1 in case below.
#include <stdio.h>
int test(const void*, const void*);
int main()
{
int a = 10, b = 5;
int result = test(&a, &b);
printf("Result: %d", result);
return 0;
}
int test(const void* a, const void* b) {
const double* da = (const double*)a;
const double* db = (const double*)b;
return (*da > * db) - (*da < *db);
}
0x0135fb00 now is my value of da and address of a
0x0135faf4 now is my value of db and address of b
From what I know, relational operators return 1 if True, 0 if False, so in this case we should have:
*da > *db --> 1
since value of da (address of a) is bigger than value of db (address of b).
*da < *db --> 0
since value of da (address of a) is not smaller than value of db (address of b).
So 1-0 is 1.
Just to specify, I've arrived at this conclusion by comparing value of da and value of db through debugger (I'm using Visual Studio with default C compiler). What am I missing?
PS: I've encountered this code on the official GNU web site.
In your question, you say:
However, as you are dereferencing the pointers (using the
*operator), the above statement instead tests whether whateverdapoints to is larger than whateverdbpoints to.If you actually want to compare the addresses, leave out the
*, i.e. :And if your end goal is to compare addresses, there's no need to cast the
voidpointers, so you can rewritetestas follows: