gpt4 book ai didi

表达式中的 Java 复合赋值运算符优先级

转载 作者:行者123 更新时间:2023-11-29 03:31:26 25 4
gpt4 key购买 nike

当我尝试执行此代码时,以下代码的输出被声明为“6”。

当我试图仔细思考这个问题时,表达式 "k += 3+++k; 应该被评估为 k = k + (3+++k); 但在这种情况下,输出应该是7. 看起来它被评估为 k = k + 3+++k; 结果是 6。

谁能解释一下为什么表达式被评估为“k + 3+++k”而不是“k + (3+++k); ?

public class TestClass {

public static int m1(int i){
return ++i;
}

public static void main(String[] args) {

int k = m1(args.length);
k += 3 + ++k;
System.out.println(k);
}

最佳答案

看看 JLS - Compound Assignment Operator 中的行为.为了回答的完整性,我将在这里引用相关的两段:

Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.

Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.

强调我的。

所以,左边的操作数首先被求值,并且只执行一次。然后,将左手操作数的评估值(在您的情况下为 1)与右手操作数的结果相加,结果为 5。因此结果 6

关于表达式中的 Java 复合赋值运算符优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18036584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com