coperatorsequalityoperator-precedenceassociativity

Operators precedence and associativity in C


"Programming With C" by Byron Gottfied has a question:

Q: What will be the output?

#include <stdio.h>
void main()
{
int a = 3, b = 2;
a = a ==b==0;
printf("%d, %d",a,b);
}

The answer is given as 1,2 ( even on codeblocks got the same answers)

Now I understand that equality operator has precedence over the assignment operator.

So it must be a == b or b == 0 first. Then as both the above have the same operator, the associativity rule causes a == b to be evaluated first.

But from here on I am lost!

How does one get to 1 and 2 as the answer?


Solution

  • I believe that the equality operator does does not have precedence over the assignment operator. C just works itself from left to right.

    in a = a == b == 0;

    a is assigned to everything on the right of the equal sign.

    On the right side of the equal sign, a == b is evaluated to false. Then we compare equality of the answer to a==b with 0. In c, 0 is equal to false, so we get true. This is our answer to "everything to the right of the equal sign". So then, we assign that value(true) to a, which is an integer. Because of automatic conversion, true is converted to 1 and assigned to a. Now a equals 1.

    As an equation, the above process can be represented as: a = (( a == b ) == 0)

    Hope this makes sense. Tell me if I need to clarify further.