Why lower precedence operator executes first? [duplicate]

送分小仙女□ 提交于 2019-12-12 03:44:56

问题


Possible Duplicate:
Problem with operator precedence

we know that precedence of prefix is greater than "LOGICAL AND" (&&) and precedence of "LOGICAL AND" is greater than "LOGICAL OR" (||).

Below program seems to violate it:

int main()

{
    int i=-3,j=2,k=0,m;
    m=++i||++j&&++k;
    printf("%d %d %d %d",i,j,k,m);
    return 0;
}

If precedence of ++ is more than && and || then all prefix should execute first. After this i=-2,j=3,k=1 and then && will execute first. why output shows : -2 2 0 1 ?

The behavior of the program is also same on ubuntu v12.04.


回答1:


The && and || operators are "short-circuiting". That is, if the value on the left is FALSE for && or TRUE for || then the expression on the right is not executed (since it's not needed to determine the value of the overall expression).




回答2:


It's correct because Short-circuiting definition.

m = ++i||++j&&++k

First, left part ++i is always TRUE so now i is -2 and it doesn't execute the right part of expression, the value of j,k don't change.



来源:https://stackoverflow.com/questions/12152143/why-lower-precedence-operator-executes-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!