Objective-C 对相同值的三向比较结果为“否” - 为什么?

发布于 2024-12-20 13:10:43 字数 393 浏览 1 评论 0原文

考虑到所有三个变量都具有相同的值,人们会期望以下比较结果为“是”:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

丑疤怪 2024-12-27 13:10:43

您的猜测完全正确,它将获取第一次比较的结果,并将其与第三个值进行比较。为此,您需要执行

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);

眸中客 2024-12-27 13:10:43

其他发帖者已经提供了答案,所以我只引用规范中确认它的相关部分:

==(等于)和 !=(不等于)运算符与关系运算符类似,只是它们的优先级较低。如果指定的关系为 true,则每个运算符生成 1;如果指定的关系为 false,则每个运算符生成 0。

相等是左结合的,因此它被解释为:

count1 == count2 == count3
(count1 == count2) == count3
(1) == count3
0

The other posters have already provided the answer, so I'll just quote the relevant part of the spec that confirms it:

The == (equal to) and != (not equal to) operators are analogous to the relational operators except for their lower precedence. Each of the operators yields 1 if the specified relation is true and 0 if it is false.

Equality is left associative, so it's interpreted as:

count1 == count2 == count3
(count1 == count2) == count3
(1) == count3
0
晨曦慕雪 2024-12-27 13:10:43

== 等比较运算符的工作方式与 C 和其他类 C 语言中的不同。

更改:

BOOL countEqual = (count1 == count2 == count3);

至:

BOOL countEqual = (count1 == count2 && count2 == count3);

Comparison operators such as == do not work like that in C and other C-like languages.

Change:

BOOL countEqual = (count1 == count2 == count3);

to:

BOOL countEqual = (count1 == count2 && count2 == count3);
波浪屿的海角声 2024-12-27 13:10:43

你猜对了。将第一次比较的结果与第三值进行比较。这不是你想要的。

You're guessing right. The result of the first comparison is compared to the third value. This is not what you want here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文