为什么在&,&,||的情况下输出不同? [英] Why is the output different in case of &&, &, ||?
问题描述
这是代码段
您能解释一下输出为何变化的原因吗
Can you explain why outputs are varying
1)
public static ShortCkt {
public static void main(String args[]) {
int i = 0;
boolean t = true;
boolean f = false, b;
b = (t && ((i++) == 0));
b = (f && ((i+=2) > 0));
System.out.println(i);
}
}
在这种情况下的输出为1
output in this case is 1
2)
public static ShortCkt {
public static void main(String args[]) {
int i = 0;
boolean t = true;
boolean f = false, b;
b = (t & ((i++) == 0));
b = (f & ((i+=2) > 0));
System.out.println(i);
}
}
在这种情况下的输出为3
output in this case is 3
3)
public static ShortCkt {
public static void main(String args[]) {
int i = 0;
boolean t = true;
boolean f = false, b;
b = (t || ((i++) == 0));
b = (f || ((i+=2) > 0));
System.out.println(i);
}
}
在这种情况下的输出为2
output in this case is 2
4)
public static ShortCkt {
public static void main(String args[]) {
int i = 0;
boolean t = true;
boolean f = false, b;
b = (t | ((i++) == 0));
b = (f | ((i+=2) > 0));
System.out.println(i);
}
}
在这种情况下的输出为3
output in this case is 3
推荐答案
为什么在&&,&,||情况下输出不同? ?
Why is the output different in case of &&, &, || ?
就像在C/C ++中一样,&&
被懒惰"地求值,而&
则不被求值.
Just as in C/C++ &&
is evaluated "lazily" while &
is not.
如果a
为false,则a && b
将返回false,甚至不评估b
.
If a
is false then a && b
will return false without even evaluating b
.
a || b
也是如此:如果第一个操作数a
为true,则整个表达式为true,而第二个操作数b
则从不求值.对于a | b
,将同时评估a
和b
.
Same goes for a || b
: If the first operand, a
is true, the whole expression is true and the second operand, b
is never evaluated. For a | b
however, both a
and b
will be evaluated.
如果使用&&
(或||
)时未求值的操作数具有副作用,则会产生后果.
This has consequences if the operand that's not being evaluated when using &&
(or ||
) has side effects, as in your examples.
侧面说明:很少有Java程序员知道^
(xor)也适用于布尔值. (^^
版本不仅仅因为它是多余的就不存在.)
Side note: Few java-programmers know that ^
(xor) works for booleans as well. (A ^^
version does not exist simply because it would be redundant.)
这篇关于为什么在&,&,||的情况下输出不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!