Precendence vs short-circuiting in C [closed]

元气小坏坏 提交于 2019-12-04 07:16:13

问题


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

Since ++ has more precedence than || and && in C, they are evaluated first and therefore the expression becomes m = -2 || 3 && 1. Now you can apply short circuiting but that produces incorrect answer. Why is that?


回答1:


Precedence ≠ order of evaluation.

The short-circuiting behavior of || and && means that their left-hand sides are evaluated first, and

  • If the LHS of || evaluates to true (nonzero), the RHS is not evaluated (because the expression will be true no matter what the RHS is)
  • If the LHS of && evaluates to false (or zero), the RHS is not evaluated (because the expression will be false no matter what the RHS is)

In your example, ++i gets evaluated, and is equal to -2, which is nonzero, so the right-hand side of the || (that is, ++j && ++k) never gets evaluated: j and k are never incremented.




回答2:


The ++s don't execute before the expression. Only ++i executes, which indicates that the result of the expression will be 1, therefore the rest of the expression is not evaluated (short circuit).

Your code is equivalent to:

if (++i)
    m = 1;
else
    if (!++j)
        m = 0;
    else if (!++i)
        m = 0;
    else
        m = 1;

This means that once ++i is evaluated to true, the else part is never executed.



来源:https://stackoverflow.com/questions/11033313/precendence-vs-short-circuiting-in-c

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