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++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01