【问题标题】:Mixing short-circuit operators with other operators将短路运算符与其他运算符混合
【发布时间】:2021-10-27 16:11:30
【问题描述】:

假设如下表达式:

public class OperatorTest {

public static void main(String[] args) {
    int x = 0;
    int y = 0;

    if(0 == 0 || ++y == 1) {
        // Some other logic here
    }

    System.out.println(y);
}

}

输出为 0。我理解短路运算符,因为 || 的右侧不会执行,因为左侧的计算结果为真。但是,++ 优先于短路逻辑运算符,所以 ++ 运算符不应该在逻辑运算符被评估之前评估吗?注意:我可能不需要在现实世界中这样做;这是我正在学习的认证考试。

【问题讨论】:

    标签: java operators


    【解决方案1】:

    短路逻辑运算符在短路时甚至不计算右侧。这由 JLS, Section 15.24 覆盖,它覆盖了 || 运算符。

    在运行时,首先计算左侧操作数表达式;如果结果的类型为Boolean,则进行拆箱转换(第 5.1.8 节)。

    如果结果值为true,则条件或表达式的值为true,并且右侧操作数表达式未计算。

    (我的粗体强调)

    所以,++y 永远不会被评估,y 仍然是0。

    当左侧计算结果为 false 时,&& 运算符存在相同的短路行为。

    【讨论】:

    • 我喜欢对 Java 语言规范的引用。
    【解决方案2】:

    较高优先级的运算符更紧密地保留它们的参数,就好像存在括号一样。你的代码相当于这个:

    public static void main (String[] args)
    {
        int x = 0;
        int y = 0;
    
        if (0 == 0)
        {
            // Some other logic here
        }
        else if (++y == 1)
        {
            // Some other logic here
        }
        System.out.println (y);
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-01
      • 2018-06-14
      • 1970-01-01
      • 2015-09-26
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      • 2012-02-04
      相关资源
      最近更新 更多