Why isn't the value of y incremented after this, z = ++x||++y&&++z?

Why is the following program giving the output as y = 1 instead of y = 2?

1
2
3
4
  int x,y,z;
  x = y = z = 1;
  z = ++x||++y&&++z;
  printf("%d",y);
For the built-in logical OR operator, the result is true if either the first or the second operand (or both) is true.
If the first operand is true, the second operand is not evaluated. http://en.cppreference.com/w/cpp/language/operator_logical
But the preference of operator && is higher than||. Thus it should be evaluated first and y should be incremented. Isn't that so?
Last edited on
Precedence of && is higher than ||

So: ++x || ++y && ++z is parsed as ++x || ( ++y && ++z )

ie. evaluate ( ++y && ++z ) only if bool(++x) is false.
Don't confuse operator precedence with the order in which the code is executed. It's two different things.

++x || ++y && ++z
is equivalent to
++x || (++y && ++z)
. The way the || operator works is that it only evaluates the second argument if the first argument evaluates to false. Just think about it. If the first argument is true then there is no point evaluating the second argument because it already knows it should return true in that case.
Topic archived. No new replies allowed.