问题描述
不假思索我写了一些code,检查一个结构的所有值设置为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);
}
,所有结构成员无符号短。我用code作为一个大型测试的一部分,但注意到它正在恢复为都等于零值假从零不同的值,和真正的 - 与我期望的相反
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.
我改变了code阅读:
I changed the code to read:
bool IsValid() {
return (0 != year) || (0 != month) || (0 != day) || (0 != hour) || (0 != minute) || (0 != second);
}
不过,想知道是什么引起的古怪行为。它是precedence的结果?我试图谷歌这个答案却一无所获,如果有任何术语来形容我很想知道它的结果。
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的code。
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 == ==Ÿž是的不的等同于 X == Y'放大器;&放;点¯x==ž你似乎期待。
In general, x == y == z
is not equivalent to x == y && x == z
as you seem to expect.
这篇关于链接布尔值给出相反的结果预期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!