Unexpected output in C program

150 Views Asked by At

I run the following C program

#include <stdio.h>

int main() {
    int x = 5, y = 6, z = 3, i;
    i = y > x > z;
    printf("%d\n", i);
}

and get the output as 0. Again, when I run

 #include <stdio.h>

 int main() {
     int x = 5, y = 6, z = 3, i;
     i = y > x && x > z;
     printf("%d\n", i);
 }

I get output as 1. Can anyone explain the logic behind this?

2

There are 2 best solutions below

2
On BEST ANSWER
i = y > x > z;

In first example, associativity of > operator left to right, So, First parsed y > x and gives boolean result.

y > x = 6 > 5 = True

then,

1(True) > 3 = False

So, output 0.

In Second,

i = y > x && x > z;

> operator higher precedence then && operator. So, first parsed y > x and if condition True, then check x > z.

2
On

Relational operators are associated from left to right. Therefore i = y > x > z; will be parsed as

i = ( (y > x) > z ) => ( (6 > 5) > 3 ) => ( 1 > 3 ) => 0

and i = y > x && x > z; will be parsed as

i = (y > x) && (x > z) => (6 > 5) && (5 > 3) => 1 && 1 => 1 

That said, in C y > x > z doesn't check if x is greater than z and less than y. But y > x && x > z does.


Note that relational operators return either 0 or 1 depending if the relation between the operands are false or true.