问题描述
我在C语言编程初学者,最近我看了逻辑和&放大器;&安培;
运营商
I am beginner in C programming language, recently I have read about Logical AND &&
operator.
我也知道,在C语言所有非零值被当成 TRUE
I also know that, in C programming language all non-zero values are treated as TRUE.
NON-ZERO && NON-ZERO = 1
NON-ZERO && ZERO = 0
ZERO && NON-ZERO = 0
ZERO && ZERO = 0
但是,当我处理下面的程序,然后我没有得到预期的答案。
But when I am dealing with the following program then I am not getting expected answer.
int main(){
int x, y, z;
x = y = z = -1;
y = ++x && ++y && ++z;
printf("x = %d, y = %d, z = %d, x, y, z);
return 0;
}
我期待
x = 0, y = 0, z = 0
但得到的答复是
x = 0, y = 0, z = -1
任何人都可以请解释一下,为什么我得到这个答案?
Can anyone please explain, Why I am getting this answer?
推荐答案
,当 X
是 0
,是
和ž
并不真正需要的,因为 0放大器进行评估;&安培; ANYTHING
是 0
。
Because of Short-circuit evaluation, when x
is 0
, y
and z
don't really need to be evaluated since 0 && ANYTHING
is 0
.
在 X
递增到 0
,结果是 0
,这就是是
得到。
Once x
is incremented to 0
, the result is 0
, and that's what y
gets.
以Z
保持不变( 1
)。
x | y | z
----+----+-----
-1 | -1 | -1 //x = y = z = -1;
0 | -1 | -1 //++x && ... Now the whole expression is evaluated to 0
0 | 0 | -1 //y = ++x && ++y && ++z;
这篇关于的&放行为;&安培;在C语言编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!