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.
这篇关于链接布尔值给出与预期相反的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:链接布尔值给出与预期相反的结果


基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01