views:

284

answers:

4

I am trying to establish equality of three equal variables, but the following code is not printing the obvious true 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))
+16  A: 
  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 ;)

Kornel Kisielewicz
Is coding like if ( (i==j) == (j==k)) okay ???
Manav MN
jmucchiello
GMan
No. (i==j) == (j==k) is equivalent to (i==j) ^ (j==k). which means it will be true if i==j and j==k or if i!=j and j!=k.Because (i==j) returns a true or false value.
SurDin
@SurDin, they're not equivalent, they are in fact quite opposite (and only if I ignore the types of the results).
avakar
Sorry, ! (..^..) :)
SurDin
+8  A: 

You need to separate the operations:

  if ( i == j && i == k)
Vincent Ramdhanie
+7  A: 

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.

FrustratedWithFormsDesigner
And it's more clear. Readability is key.
Mike Pateras
Just to be picky, the compiler is actually warning that you're *comparing a comparison*.
jleedev
Although that's obviously the meaning Manav intended, that's not the change the compiler suggested. Heeding the compiler's warning would give you this code: `(i == j) == k`.
Rob Kennedy
True: although the compiler said `suggest parentheses around comparison in operand of ‘==’` but since it didn't specify WHICH '==', I just parenthesised both of 'em! ;)
FrustratedWithFormsDesigner
More importantly, it does the right thing, while `i == j == k` doesn't.
Mike Seymour
+5  A: 

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

Tadeusz Kopec