Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

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

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
");
        else
                printf("NOT Equal
");
        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))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  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 ;)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...