Objective-C 对相同值的三向比较结果为“否” - 为什么?
考虑到所有三个变量都具有相同的值,人们会期望以下比较结果为“是”:
NSUInteger count1 = 2;
NSUInteger count2 = 2;
NSUInteger count3 = 2;
BOOL countEqual = (count1 == count2 == count3);
// but: countEqual = NO
唉 countEqual 为“否”,我想更好地理解为什么以及这个特定问题是否也出现在 C 或 C++ 代码中?
我的猜测是:
(count1 == count2) --> YES (1)
(YES == count3) or (1 == count3) --> NO (0)
Considering that all three variables have identical values, one would expect the following comparison to result in YES:
NSUInteger count1 = 2;
NSUInteger count2 = 2;
NSUInteger count3 = 2;
BOOL countEqual = (count1 == count2 == count3);
// but: countEqual = NO
Alas countEqual is NO and I'd like to better understand why and whether this particular issue also appears in C or C++ code?
My guess is:
(count1 == count2) --> YES (1)
(YES == count3) or (1 == count3) --> NO (0)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的猜测完全正确,它将获取第一次比较的结果,并将其与第三个值进行比较。为此,您需要执行
countEqual = (count1 == count2) && (计数1 == 计数3);
Your guess is exactly correct, it will take the result from the first comparison, and compare it to the 3rd value. To do this you would need to do
countEqual = (count1 == count2) && (count1 == count3);
其他发帖者已经提供了答案,所以我只引用规范中确认它的相关部分:
相等是左结合的,因此它被解释为:
The other posters have already provided the answer, so I'll just quote the relevant part of the spec that confirms it:
Equality is left associative, so it's interpreted as:
==
等比较运算符的工作方式与 C 和其他类 C 语言中的不同。更改:
至:
Comparison operators such as
==
do not work like that in C and other C-like languages.Change:
to:
你猜对了。将第一次比较的结果与第三值进行比较。这不是你想要的。
You're guessing right. The result of the first comparison is compared to the third value. This is not what you want here.