polerto
polerto

Reputation: 1790

Using an union, can I compare two doubles via unsigned int?

Having the following unions:

union {double first_d; uint64 first;};
union {double second_d; uint64 second;};
...
first_d = <a double value>
second_d = <a double value>

Does the output of following comparisons:

if(first_d > second_d)
    // CASE 1 OUTPUT
else if(first_d < second_d)
    // CASE 2 OUTPUT
else
    // CASE 3 OUTPUT

always the same for the following?

if(first> second)
    // CASE 1' OUTPUT
else if(first < second)
    // CASE 2' OUTPUT
else
    // CASE 3' OUTPUT

Upvotes: 1

Views: 373

Answers (1)

Mysticial
Mysticial

Reputation: 471479

Nope. Here's a counter-example using NaNs:

int main()
{

    union {double first_d; uint64 first;};
    union {double second_d; uint64 second;};

    first  = 0x7ff8000000000001;
    second = 0x7ff8000000000002;

    if(first_d > second_d)
        printf("greater\n");
    else if(first_d < second_d)
        printf("less\n");
    else
        printf("other\n");

    if(first > second)
        printf("greater\n");
    else if(first < second)
        printf("less\n");
    else
        printf("other\n");

    return 0;
}

Output:

other
less

I'll also mention that type-punning via unions isn't 100% standard conformant. So you could also say it's undefined behavior.

Upvotes: 2

Related Questions