Question about x=y==z [closed]
I have the following code:
#include <stdio.h>
int main(void)
{
int x = 2, y = 6, z = 6;
x = y == z;
printf("%d", x);
}
output is = 1
Why?
Because the assignment is right to left, and the precedence of == is greater than =.
it is x = (y == z)
y == z is 1.
From the precedence table ==
is having a higher precedence from =
Hence
x = y == z;
is same as:
x = (y == z);
Since y == z
is true (1), x
gets 1
.
x = y == z
is read as x = (y == z)
, and y and z both are 6 and thus they are equal. true
is 1, so x is 1.
y == z
evaluates to true, which you are assigning to x
...x = true
casts to a value of 1 because x
is of type int
.
y == z => 6 == 6 => True
True represented as integer (%d) is 1.
x = y == z;
is the same thing as x = (y == z);
and as y == 6
and z == 6
, (y == z) == 1
so x == 1
It evals == operator first, so since y==z is true, and x is int,x is set to 1 (true)
Comparison (==
) has higher precedence than assignment (=
), so your middle statement is processed as x = ( y == z )
; and the result of a true comparison is 1, which is assigned to x.
== have higher precedence than =. So x = y == z is actually x = (y == z). Now y and z both are 6. So the comparison is true and outcome is 1 which is set to x.
精彩评论