假设 i=0 并且数组的所有元素都初始化为 0 a[i++] = a[i++] + 2;
What's the order of evaluation for this line assuming i=0 and all elements of array are initialized to 0 a[i++] = a[i++] + 2;
我在 java in nutshell 书中看到了这行代码,我想知道编译器是如何划分这段代码的
a[i++] += 2;
a[i++] = a[i++] + 2;
15.26.1. Simple Assignment Operator =
If the left-hand operand is an array access expression (§15.10.3), possibly enclosed in one or more pairs of parentheses, then:
First, the array reference subexpression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the index subexpression (of the left-hand operand array access expression) and the right-hand operand are not evaluated and no assignment occurs.
Otherwise, the index subexpression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and the right-hand operand is not evaluated and no assignment occurs.
https://docs.oracle.com/javase/specs/jls/se12/html/jls-15.html#jls-15.26.1
我假设评估的顺序应该如下
a[i++] = a[i++] + 2;
^ ^ ^
1 3 2
----------
^
4
------
^
5
--------------------
^
6
我们可以通过运行这个片段
来证明
int[] a = {0, 10, 0, 0};
int i = 0;
a[i++] = a[i++] + 2;
System.out.println(Arrays.toString(a)); // [12, 10, 0, 0]
System.out.println(i); // 2
我在 java in nutshell 书中看到了这行代码,我想知道编译器是如何划分这段代码的
a[i++] += 2;
a[i++] = a[i++] + 2;
15.26.1. Simple Assignment Operator =
If the left-hand operand is an array access expression (§15.10.3), possibly enclosed in one or more pairs of parentheses, then:
First, the array reference subexpression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the index subexpression (of the left-hand operand array access expression) and the right-hand operand are not evaluated and no assignment occurs.
Otherwise, the index subexpression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and the right-hand operand is not evaluated and no assignment occurs.
https://docs.oracle.com/javase/specs/jls/se12/html/jls-15.html#jls-15.26.1
我假设评估的顺序应该如下
a[i++] = a[i++] + 2;
^ ^ ^
1 3 2
----------
^
4
------
^
5
--------------------
^
6
我们可以通过运行这个片段
来证明int[] a = {0, 10, 0, 0};
int i = 0;
a[i++] = a[i++] + 2;
System.out.println(Arrays.toString(a)); // [12, 10, 0, 0]
System.out.println(i); // 2