它的正确答案是 22。但我得到 24。我哪里错了?我最后评估赋值运算符 += 因为它具有最低的优先级

Its correct answer is 22. But I am getting 24. Where am I wrong? I evaluate the assignment operator += in last as it has the lowest precedence

class Output
{    
    public static void main (String[] args)   
    {
        int a = 5;
    
        a += 5+ (++a) + (a++);
        System.out.print(a);
    }
}

评价:

a += 5 + (++a) + (a++)

=> a+= 5 + 6 + (a++) [++a :increment value of a and then use it. So:increment a = 6, then use a=6]

=> a+= 5 + 6 + 6 [a++ :use and then increment value of a. So: use a=6, then increment a=7]
    
=> a+= 11 + 6
    
=> a+= 17
    
=> a = a+17
    
=> a = 7 + 17
    
=> a = 24

+= 运算符,与所有复合运算符一样,先计算左侧的变量 ,然后再计算所有其他操作数,然后再实际执行任何操作。这是由 JLS, Section 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.

(大胆强调我的)

这意味着 a 被评估(并保存)到左侧的 5 之前 a++++a 在右侧进行评估。右侧确实计算为 17,但因为左侧仍然是 5,总和是 22,而不是 24

表达式

a += 5 + (++a) + (a++);

等同于

a = a + 5 + (++a) + (a++);

意味着a的新赋值是从右到左的操作数之和(因为从左到右结合性)在以下方式:

  • 取变量a:求值为5
  • 添加常量5
  • 增加变量 a 然后 评估结果:6
  • 评估变量 a 然后 增加它。 和中使用的值将是评估值: 6

总和为22