2

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?

haccks
  • 104,019
  • 25
  • 176
  • 264
  • 4
    `6 > 5 == 1`-> `1 > 3 == 0` – UnholySheep May 09 '17 at 12:17
  • If you understand how these operators work, it should be pretty self-explanatory. The only thing that might be somewhat subtle here is operator associativity, where the relational operators guarantee left-to-right. That is, the expression is guaranteed to be equivalent to `(y > x) > z`. – Lundin May 09 '17 at 12:45

2 Answers2

10

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.

haccks
  • 104,019
  • 25
  • 176
  • 264
  • 2
    I was just gonna post the same thing. I'm too slow at typing – Manav Dubey May 09 '17 at 12:18
  • 2
    The answer could be improved by: Mentioning that operator associativity is left to right for `>`. Also mention/link the operator precedence/associativity table so that OP can learn how to find the same information for other operators. – Klas Lindbäck May 09 '17 at 12:24
1
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.

msc
  • 33,420
  • 29
  • 119
  • 214
  • Nit-pick: operator precedence and associativity dictate the order in which the expression is _parsed_, not evaluated. The order of evaluation is unspecified. That is, given `y() > x() > z()`, you cannot know the order in which the functions are executed. Only that the results from y() and x() are used with `>` before the result of that is compared with the result from z(). – Lundin May 09 '17 at 12:48
  • @Lundin Thanks!!, I have edited my answer. – msc May 09 '17 at 12:51