0

i would be grateful if somebody could help me with this problem. The book I am currently reading 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?

2 Answers2

1

See https://en.cppreference.com/w/cpp/language/operator_precedence

Note the line that says, "Operators that have the same precedence are bound to their arguments in the direction of their associativity." You can see the associativity for each operator on the far right column.

Note that equality operator is on line 10, with associativity left-to-right.
Note that assignment is line 16, so it has lower precedence than equality.

// original
a = a == b == 0

// precedence rule
a = (a == b == 0)

// associativity rule
a = ((a == b) == 0)
Kenny Ostrom
  • 5,639
  • 2
  • 21
  • 30
0

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.