1

具有以下工会:

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

是否输出以下比较:

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

以下总是相同的?

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

1 回答 1

2

没有。这是一个使用的反例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;
}

输出:

other
less

我还要提到通过联合的类型双关语不是 100% 符合标准的。所以你也可以说这是未定义的行为。

于 2012-09-16T21:42:46.087 回答