3

Possible Duplicate:
why "++x || ++y && ++z" calculate "++x" firstly ? however,Operator "&&" is higher than "||"

The following program does not seem to work as expected. '&&' is to have higher precendence than '||', so the actual output is confusing. Can anyone explain the o/p please?

#include <stdio.h>

int main(int argc, char *argv[])
{
    int x;
    int y;
    int z;

    x = y = z = 1;

    x++ || ++y && z++;

    printf("%d %d %d\n", x, y, z);

    return 0;
}

The actual output is: 2 1 1

TIA.

Community
  • 1
  • 1
Quiescent
  • 1,088
  • 7
  • 18

3 Answers3

5

Precedence and order of evaluation have no relation whatsoever.

&& having higher precedence than || means simply that the expression is interpreted as

x++ || (++y && z++);

Thus, the left-hand operand of || is evaluated first (required because there is a sequence point after it), and since it evaluates nonzero, the right-hand operand (++y && z++) is never evaluated.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
2

The confusing line is parsed as if it were:

x++ || (++y && z++);

Then this is evaluated left-to-right. Since || is a short-circuit evaluator, once it evaluates the left side, it knows that the entire expression will evaluate to a true value, so it stops. Thus, x gets incremented and y and z are not touched.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
1

The operator precedence rules mean the expression is treated as if it were written:

x++ || (++y && z++);

Since x++ is true, the RHS of the || expression is not evaluated at all - hence the result you see.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278