tags:

views:

169

answers:

9

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?

+4  A: 

Because the assignment is right to left, and the precedence of == is greater than =.

it is x = (y == z)

y == z is 1.

Marco
+1  A: 

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.

Thomas Lötzer
A: 

x = y == z; is the same thing as x = (y == z); and as y == 6 and z == 6, (y == z) == 1 so x == 1

Colin Hebert
+1  A: 

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.

JCD
There is no cast, right? Tagged as C and C does not have a boolean type.
Ishtar
Oh, you are both wrong. C *does* have a boolean type, yet there is no cast here.
Johannes Schaub - litb
A: 

It evals == operator first, so since y==z is true, and x is int,x is set to 1 (true)

FallenAngel
+1  A: 

y == z => 6 == 6 => True

True represented as integer (%d) is 1.

Serkan
+2  A: 

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.

codaddict
A: 

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.

Scott Thomson
A: 

== 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.

taskinoor