问题描述
我正在Stack Overflow上搜索此问题的答案,但我没有找到确切的答案.我想出了这段代码.我知道操作员应该如何工作,但在这种问题上我不理解他们.例如,在第一种情况下,如果我正在使用++y
和++z
,z
和y
怎么仍为1?
I was searching on Stack Overflow for the answer to this question but I haven't found an exact answer. I came up with this code. I know how operators are supposed to work but I don't understand them in this kind of problem. For example, in the first case, how can z
and y
still be 1 if there I am using ++y
and ++z
?
#include <stdio.h>
int main(void) {
int x, y, z;
x = y = z = 1;
++x || ++y && ++z;
printf("x = %d y = %d z = %d\n", x, y, z);
x = y = z = 1;
++x && ++y || ++z;
printf("x = %d y = %d z = %d\n", x, y, z);
x = y = z = 1;
++x && ++y && ++z;
printf("x = %d y = %d z = %d\n", x, y, z);
x = y = z = -1;
++x && ++y || ++z;
printf("x = %d y = %d z = %d\n", x, y, z);
x = y = z = -1;
++x || ++y && ++z;
printf("x = %d y = %d z = %d\n", x, y, z);
x = y = z = -1;
++x && ++y && ++z;
printf("x = %d y = %d z = %d\n", x, y, z);
return 0;
}
结果我得到:
x = 2 y = 1 z = 1
x = 2 y = 2 z = 1
x = 2 y = 2 z = 2
x = 0 y = -1 z = 0
x = 0 y = 0 z = -1
x = 0 y = -1 z = -1
推荐答案
这是对逻辑表达式求值的结果:一旦确定表达式为假(或真),其余运算符即为不再进行评估.例如:
This is a result of the evaluation of the logical expressions: as soon as it has been determined that an expression is false (or true), the remaining operators are not evaluated anymore. E.g.:
++x || ++y && ++z;
由于x
为1,所以表达式将为true,而与z
或y
无关,因此不再执行++y
和++z
.
As x
is one, the expression will be true independent of what z
or y
are, so ++y
and ++z
are not performed anymore.
这篇关于一行代码中有多个逻辑运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!