1

Why does the following expression evaluate to 0?

i > --i

Suppose i = 5. Evaluating the expression from left to right, we evaluate the left operand (i) to get 5 and we evaluate the right operand (--i) to get 4. So the expression about should evaluate to 1. But when I compile it with gcc and run it, it always evaluates to 0. Is there a flaw in my thought process?

JellalF
  • 115
  • 3

1 Answers1

11

It's simply undefined behaviour, since you are modifying the value of i as well as reading it without an intervening sequence point. The relational operator < does not introduce a sequence point.

From C11, 6.5(2):

If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • +1. `--i` is performed before the value of `i` is used on *the right hand side*, but says nothing about what the value of `i` is on the *left hand side*. – Greg Hewgill May 12 '12 at 23:12
  • 2
    @BinyaminSharet No, C does not specify the order of evalation within a subexpression. You do not know if the left side(that's the leftmost `i` in `i > --i` is evaluated first, or if the right side of the `>` is evaluated first. – nos May 12 '12 at 23:13
  • What about (i > i++)? Let i = 5. i++ still gets evaluated first, but it returns 5, then i evaluates to 6, so the result should be 1, but a quick compile & run reveals that it evaluates to 0. – JellalF May 12 '12 at 23:19
  • @JellalFernandes: Same problem. – Kerrek SB May 12 '12 at 23:19