两个'=='相同“if”中的相等运算符条件没有按预期工作
我试图建立三个相等变量的相等性,但以下代码没有打印它应该打印的明显正确答案。有人可以解释一下,编译器如何在内部解析给定的 if(condition)
吗?
#include<stdio.h>
int main()
{
int i = 123, j = 123, k = 123;
if ( i == j == k)
printf("Equal\n");
else
printf("NOT Equal\n");
return 0;
}
输出:
manav@workstation:~$ gcc -Wall -pedantic calc.c
calc.c: In function ‘main’:
calc.c:5: warning: suggest parentheses around comparison in operand of ‘==’
manav@workstation:~$ ./a.out
NOT Equal
manav@workstation:~$
编辑:
根据下面给出的答案,以下语句可以检查上述相等性吗?
if ( (i==j) == (j==k))
I am trying to establish equality of three equal variables, but the following code is not printing the obvious correct answer which it should print. Can someone explain, how the compiler is parsing the given if(condition)
internally?
#include<stdio.h>
int main()
{
int i = 123, j = 123, k = 123;
if ( i == j == k)
printf("Equal\n");
else
printf("NOT Equal\n");
return 0;
}
Output:
manav@workstation:~$ gcc -Wall -pedantic calc.c
calc.c: In function ‘main’:
calc.c:5: warning: suggest parentheses around comparison in operand of ‘==’
manav@workstation:~$ ./a.out
NOT Equal
manav@workstation:~$
EDIT:
Going by the answers given below, is the following statement okay to check above equality?
if ( (i==j) == (j==k))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为了避免这种情况:
不要这样做:
您将得到 i = 1, j = 2, k = 1 :
... 因此是错误的答案;)
To avoid that:
Don't do this:
You'll get for i = 1, j = 2, k = 1 :
... hence the wrong answer ;)
您需要将操作分开:
You need to separate the operations:
表达式
被解析为
因此,您将
i
与j
进行比较并得到true
。然后将true
与123
进行比较。true
转换为整数,如1
。 1 不等于123
,因此表达式为 false。您需要表达式
i == j && j == k
Expression
is parsed as
So you compare
i
toj
and gettrue
. Than you comparetrue
to123
.true
is converted to integer as1
. One is not equal123
, so the expression is false.You need expression
i == j && j == k
我会注意编译器的警告并将其写为
(i==j) && (j==k)
。写起来需要更长的时间,但它意味着同样的事情,并且不太可能让编译器抱怨。I'd heed the compiler's warning and write it as
(i==j) && (j==k)
. It takes longer to write but it means the same thing and is not likely to make the compiler complain.