Two '==' equality operators in same 'if' condition are not working as intended

依然范特西╮ 提交于 2019-11-27 04:50:51

问题


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

回答1:


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

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

To avoid that:

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

Don't do this:

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

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

 if ( (false) == (false) )

... hence the wrong answer ;)




回答2:


You need to separate the operations:

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



回答3:


Expression

i == j == k

is parsed as

(i == j) == k

So you compare i to j and get true. Than you compare true to 123. true is converted to integer as 1. One is not equal 123, so the expression is false.

You need expression i == j && j == k




回答4:


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.



来源:https://stackoverflow.com/questions/2155280/two-equality-operators-in-same-if-condition-are-not-working-as-intended

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!