问题
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 betrue
no matter what the RHS is) - If the LHS of
&&
evaluates to false (or zero), the RHS is not evaluated (because the expression will befalse
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