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
  • 856
  • 5
  • 16
  • Another one http://stackoverflow.com/questions/7212482/problem-with-operator-precedence – AnT Sep 09 '11 at 03:46

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
  • 201,833
  • 32
  • 354
  • 689
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
  • 227,407
  • 48
  • 383
  • 507
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
  • 698,132
  • 130
  • 858
  • 1,229