链接布尔值给出与预期相反的结果

我不假思索地编写了一些代码来检查结构的所有值是否都设置为 0.为此我使用了:

Unthinkingly I wrote some code to check that all the values of a struct were set to 0. To accomplish this I used:

bool IsValid() {
    return !(0 == year == month == day == hour == minute == second);
}

其中所有结构成员都是无符号短类型.我将代码用作更大测试的一部分,但注意到它对于不为零的值返回 false,对于所有等于零的值返回 true - 与我的预期相反.

where all struct members were of type unsigned short. I used the code as part of a larger test but noticed that it was returning false for values differing from zero, and true for values that were all equal to zero - the opposite of what I expected.

我把代码改成了:

bool IsValid() {
    return (0 != year) || (0 != month) || (0 != day) || (0 != hour) || (0 != minute) || (0 != second);
}

但想知道是什么导致了奇怪的行为.是优先的结果吗?我试过用谷歌搜索这个答案,但什么也没找到,如果有任何命名法来描述我很想知道的结果.

But would like to know what caused the odd behaviour. Is it a result of precedence? I've tried to Google this answer but found nothing, if there's any nomenclature to describe the result I'd love to know it.

我使用 VS9 和 VS8 编译了代码.

I compiled the code using VS9 and VS8.

推荐答案

== 从左到右分组,所以如果所有值都为零,那么:

== groups from left to right, so if all values are zero then:

0 == year // true
(0 == year) == month // false, since month is 0 and (0 == year) converts to 1
((0 == year) == month) == day // true

等等.

一般来说,x == y == z 不 等价于 x == y &&x == z 如你所料.

In general, x == y == z is not equivalent to x == y && x == z as you seem to expect.

相关文章