Chaining Bool values give opposite result to expected(链接布尔值给出与预期相反的结果)
问题描述
我不假思索地编写了一些代码来检查结构的所有值是否都设置为 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.
这篇关于链接布尔值给出与预期相反的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:链接布尔值给出与预期相反的结果


- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 近似搜索的工作原理 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 从python回调到c++的选项 2022-11-16
- Stroustrup 的 Simple_window.h 2022-01-01
- C++ 协变模板 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07