处于相同"if"条件的两个"=="相等运算符未按预期工作 [英] Two '==' equality operators in same 'if' condition are not working as intended

查看:136
本文介绍了处于相同"if"条件的两个"=="相等运算符未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图建立三个相等变量的相等性,但是以下代码并未打印出应打印的明显正确答案.有人可以解释一下,编译器如何在内部解析给定的if(condition)?

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

输出:

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:~$

按照下面给出的答案,下面的语句可以检查上述相等性吗?

Going by the answers given below, is the following statement okay to check above equality?

if ( (i==j) == (j==k))

推荐答案

  if ( (i == j) == k )

  i == j -> true -> 1 
  1 != 123 

为避免这种情况:

 if ( i == j && j == k ) {

请勿执行以下操作:

 if ( (i==j) == (j==k))

对于i = 1,j = 2,k = 1,您会得到:

You'll get for i = 1, j = 2, k = 1 :

 if ( (false) == (false) )

...因此答案错误;)

... hence the wrong answer ;)

这篇关于处于相同"if"条件的两个"=="相等运算符未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆