-4
int main()
{
    int x=35;
    printf("%d\n%d\n%d\n",x==35,x=50,x>35);
    return 0;
}

In the above main function the output comes out to be 0 50 0. Why is it so that the comparison operator is producing an output of 0 even when the value of x is equal to 35.

I am also bit confused in the output produced by x>35 because when this is compiled the value of x has been updated to 50 than why is it so that it produces an output of 0 instead of 1.

Haris
  • 12,120
  • 6
  • 43
  • 70
user3542577
  • 25
  • 1
  • 6
  • 3
    Evaluation order of `printf` parameters is *unspecified* in the standard. – Maroun Sep 06 '15 at 09:19
  • Dup: http://stackoverflow.com/questions/949433/why-are-these-constructs-using-undefined-behavior – P.P Sep 06 '15 at 09:20

2 Answers2

3

x = 50 is assignment, and apparently, the parameters are evaluated in reversed order:

so x > 35 is evaluated to false (0) first, then x=50 as assignment, which evaluates to 50 as a side effect, then x == 35 which is false (0) again.

(Indeed, like other answer says, this execution order is not specified.

Pieter21
  • 1,765
  • 1
  • 10
  • 22
  • 3
    It is actually undefined behaviour. Reading and writing to the same variable with no intervening sequence points. – juanchopanza Sep 06 '15 at 09:24
3
printf("%d\n%d\n%d\n",x==35,x=50,x>35);

It's unspecified whether x==35 or x=50 is evaluated first.

This is actually undefined behavior, you might see a different result on another machine.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294