问题
#include <stdio.h>
int main(void) {
int i = -3, j = 2, k = 0, m;
m = ++i && ++j || ++k;
printf("%d %d %d %d\n",i,j,k,m);
return 0;
}
I am trying to learn about associativity and precedence of operators in C. Here, The output comes out to be -2 3 0 1
, but I think the output should be -2 3 1 1
because k
is also pre-incremented. Why that won't be the answer? Thanks!
回答1:
the ||
has short-circuit evaluation, which means that the right hand side gets evaluated only if the left hand side is false
. In your case this doesn't happen since both i
and j
have values different than 0
after being incremented, so the ++k
doesn't get executed
The same behavior occurs when you have a &&
in which the LHS expressions evaluates to false
回答2:
The expression before the ||
is true so the part after the ||
that is the ++K does not get executed so k
wont be incremented. Hence the value of K remains 0 and the value of m is one since the left of ||
is true and true || <anything>
is always true
.
回答3:
1 || 0 = 1
and 1 || 1 = 0
So once the first condition is TRUE while evaluating statement with ||
operator there is no need to evaluate the second expression that is what is happening here.
回答4:
Don't get confused with Precedence and Order of evaluation.
The order of evaluation of logical OR ||
is left to right.
So if left = true
then left || right
will never execute right
. In your code exactly same happened.
As you know, any non zero value treated as true
in C, hence, ++i
or -2
is true
. So,
m = ++i && ++j || ++k;
m = (true && true) || bla bla bla; //right not even checked!
m = true
m = 1
And you get the output as expected.
For experiment, instead of i = -3
try i = -1
, then the scenario will be
m = ++i && ++j || ++k;
m = false && (not going to evaluate) || ++k;
m = false || true;
m = true
m = 1
And output will be: 0 2 1 1
来源:https://stackoverflow.com/questions/31265625/why-the-output-wont-be-this-in-the-code