C的短路评估 [英] Short-circuit evaluation on C
问题描述
我正在从Kelley-Pohl撰写的《关于C的书》中学习C,但是我不理解这种练习:
I'm studying C from A Book on C by Kelley-Pohl, and there's this exercise that I don't understand:
int a = 0, b = 0, x;
x = 0 && (a = b = 777);
printf("%d %d %d\n", a, b, x);
x = 777 || (a = ++b);
printf("%d %d %d\n", a, b, x);
他们只是说想想输出,然后将其与真实输出进行比较.我以为输出应该是
They just say to imagine the output and compare it to the real one. I thought the output would have been
777 777 0
777 777 0
778 778 1
778 778 1
但是是
0 0 0
0 0 0
0 0 1
推荐答案
&&
运算符使用惰性评价.如果&&
运算符的任一侧为false
,则整个表达式为false
.
The &&
operator uses lazy evaluation. If either side of the &&
operator is false
, then the whole expression is false
.
C检查运算符左侧的真实值,在您的情况下为0
.由于0
在c中为false,因此永远不会评估操作的右侧表达式(a = b = 777)
.
C checks the truth value of the left hand side of the operator, which in your case is 0
. Since 0
is false in c, then the right hand side expression of the operation, (a = b = 777)
, is never evaluated.
第二种情况类似,不同之处在于,如果左侧表达式返回true
,则||
返回true
.还要记住,在c中,任何不是0
的东西都被认为是true
.
The second case is similar, except that ||
returns true
if the left hand side expression returns true
. Also remember that in c, anything that is not 0
is considered true
.
希望这会有所帮助.
这篇关于C的短路评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!