Logical Operators and increment operators [duplicate]

我的梦境 提交于 2019-12-04 07:15:34

问题


Can anyone explain this code? How value is assigned to only variable m but the output is for all variables change. Also the roles of logical operator and increment operators over here.

#include <stdio.h>

#include <stdlib.h>
int main() 
{ 
    int i=-3, j=2, k=0, m; 
    m = ++i || ++j && ++k; 
    printf("%d%d%d%d\n", i, j, k, m); 
    return 0; 
}

回答1:


|| or logical OR operator has a short-circuit property. It only evaluated the RHS is the LHS is FALSY.

In your case, the evaluation of ++x produces a value of -2, which is not FALSY (0). Hence, the RHS is never evaluated.

To break it down:

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

 >> m = (++i) || (++j && ++k);
     >> m = (-2) || (++j && ++k);
        >> m = 1   // -2 != 0 

So, only the value of m and i are changed, remaining variables will retain their values (as they are not evaluated).

That said, the result of the logical OR operator is either 0 or 1, an integer value. The result is stored in m, in your case.



来源:https://stackoverflow.com/questions/52152793/logical-operators-and-increment-operators

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