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

标签 java primitive integer-arithmetic compound-assignment

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

    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/

相关文章:

java - 将参数传递给 TokensRegex 的正确编码是什么

java - 在Spring boot中创建外键-H2数据库

java - Java中的实例和类(静态)变量有什么区别

java - 使用 p : namespace 注入(inject)映射类型属性

java - Core Java 这个简单语法有什么问题

java - "non-zero"基元的数组是否需要更多内存?

Java - 最简单的是查找基元数组中是否存在某个位置?

c - C中没有减号的减法

c - 8051 16 位加法/乘法结果 16 位而不是 32 位

c++ - 无符号算术和整数溢出