java什么(在规范中)保证“非短路逻辑运算符实际上不会短路?”?
这是直接受到this question启发的
有许多引用/语句表明,当应用于布尔运算时,位运算符不会短路。也就是说boolean a = f() & g()
,其中f()
和g()
都返回布尔值,都将被计算
然而,JLS只说:
15.22.2 Boolean Logical Operators &, ^, and |
When both operands of a &, ^, or | operator are of type boolean or Boolean, then the type of the bitwise operator expression is boolean. In all cases, the operands are subject to unboxing conversion (§5.1.8) as necessary.For &, the result value is true if both operand values are true; otherwise, the result is false.
For ^, the result value is true if the operand values are different; otherwise, the result is false.
For |, the result value is false if both operand values are false; otherwise, the result is true.
这如何保证两个操作数都得到了实际计算?除了xor
之外,如果其中一个参数(可能是第二个/右个作为第一个被计算的参数)违反了条件,您仍然能够中断并返回结果
例如a & b
只需将b
计算为false即可将表达式计算为false
请注意:我不是问它是否以这种方式实现(不会短路)——它当然是
我在问:
Would implementing it with short circuit violate language standard?
# 1 楼答案
JLS明确规定,对条件or和条件and执行快捷方式。它用按位or/and运算符解释条件or/and的行为。因此,它强调了快捷方式是位运算符行为的一种变化
所以,我想说使用快捷方式违反了标准。这肯定会违背开发者的期望
15.24条件或运算符| |
&&;运营商就像&;(§15.22.2),但仅当其左侧操作数的值为真时,才计算其右侧操作数