0
int main()
{
    int a=0,b=0,c=0;

    if (a==b==c)
    {
         printf("111\n");
    }
    else
    {
         printf("222\n");
    }
    if (a==b)
    {
         printf("333");
    }
}

The output is

222
333

It's very clearly that, a==b==c is False and a==b is True. But I couldn't find the reason. I guess maybe a==b==c is match variables' address. I need more clue and proof.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Milky酱TH
  • 11
  • 1
  • 3
    `a == b == c` is `(a == b) == c` is either `0 == c` or `1 == c` (in the case that `a` and `b` have the same value ... is `1 == c`). The equality operator `==` yields an `int` with the value `0` or `1`. – pmg May 10 '21 at 08:10
  • 2
    It's about operator *associativity*. For the `==` operator it's left to right which leads to the situation mentioned by @pmg. – Some programmer dude May 10 '21 at 08:11
  • 1
    Just don't write code such as `a == b == c`. Weird code gives weird results. – Lundin May 10 '21 at 08:24
  • very frequent dupe. You should use SO search box above. – 0___________ May 10 '21 at 08:30

3 Answers3

2

In C, a == b == c is equivalent to (a == b) == c, where a == b yields 1 if true, 0 otherwise.

In your case, a == b is true, so a == b == c is equivalent to 1 == c, which is false.

You can further try it with:

printf("%d\n%d\n", 0 == 0, 0 == 1);

which gives the result:

1
0
NemoYuan2008
  • 265
  • 1
  • 7
0

The comparison operator == has left to right associativity.

So, an expression like

 a == b == c

is the same as

(a == b ) == c

In your case, a, b, c all having values 0, the expression turns out to be

(0 == 0) == 0

or,

  1 == 0

which yields 0 (Falsy). So, control goes to the else part.

Then, for the aforementioned reason, a == b evaluates to 1 (truthy), so the corresponding if block is executed.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

The equality operator evaluates left to right and yields 1 if the specified equality is true and 0 if it is false.

Thus the expression in the if statement

if (a==b==c)

is equivalent to

if ( ( a == b ) == c )

As a is equal to b (the both are equal to 0 ) then the first sub-expression ( a == b ) evaluates to 1 and you actually have

if ( 1 == c )

As c is equal to 0 then the expression 1 == c evaluates to 0 and the compound statement of the if statement is bypassed. As a result the sub-statement of the else statement is executed

printf("222\n");

Maybe the author of the code meant the following if statement

if ( ( a == b ) && ( b == c ) )

In this case as a is equal to b and b is equal to c then this condition evaluates to logical true.

On the other hand, as a is equal to b then this if statement is also executed.

if (a==b)
{
     printf("333");
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335