Relational operators

85 Views Asked by At

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.

1

There are 1 best solutions below

3
bool3max On

In your question, you say:

*da > *db --> 1

since value of da (address of a) is bigger than value of db (address of b).

However, as you are dereferencing the pointers (using the * operator), the above statement instead tests whether whatever da points to is larger than whatever db points to.

If you actually want to compare the addresses, leave out the *, i.e. :

(da > db) - (da < db)

And if your end goal is to compare addresses, there's no need to cast the void pointers, so you can rewrite test as follows:

int test(const void *a, const void *b) {
    return (a > b) - (a < b);
}