gpt4 book ai didi

java - Java 中复合赋值(+=、-=、*=、...)的混淆

转载 作者:行者123 更新时间:2023-12-02 02:31:36 25 4
gpt4 key购买 nike

我对以下代码的结果有点困惑:

    int x = 1;
x -= ((x += 1) << 1);
System.out.println(x);

它打印出 -3,但我希望它打印出 -2,因为在我看来,计算应该是这样的:

| Opearation | Returned | x |
+------------+----------+---+
| int x = 1; | - | 1 |
+------------+----------+---+
| (x += 1) | 2 | 2 |
+------------+----------+---+
| (2 << 1) | 4 | 2 |
+------------+----------+---+
| x -= 4; | - |-2 |

我在这里缺少什么?有人可以向我解释一下发生了什么事吗?

谢谢!

最佳答案

JLS 15.26.2 表示如下:https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.26.2

If the left-hand operand expression is not an array access expression, then:

First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs.

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.

Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion (§5.1.13) to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.

因此,x 的原始值(即 1)被保存,然后计算 RHS。因此它是-3

关于java - Java 中复合赋值(+=、-=、*=、...)的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47005484/

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