开发者

Operator precedence in C [duplicate]

This question already has answers here: Closed 11 years ago.

Pos开发者_如何学Pythonsible 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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜