问题
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