Java - 操作顺序 - 在一行中使用两个赋值运算符 [英] Java - Order of Operations - Using Two Assignment Operators in a Single Line
问题描述
在一行中使用两个赋值运算符时的操作顺序是什么?
What are the order of operations when using two assignment operators in a single line?
public static void main(String[] args){
int i = 0;
int[] a = {3, 6};
a[i] = i = 9; // this line in particular
System.out.println(i + " " + a[0] + " " + a[1]);
}
感谢您的帖子.我知道 = 从右边取值,但是当我编译它时,我得到:
Thanks for the posts. I get that = takes values from the right, but when I compile this I get:
9 9 6
我认为它会是 ArrayOutOfBounds 异常,但它正在分配 'a[i]' 之前它正在移动到 9.它只是为数组这样做吗?
I thought it would have been and ArrayOutOfBounds exception, but it is assigning 'a[i]' before it's moving over the 9. Does it just do that for arrays?
推荐答案
=
被解析为右结合,但求值顺序是从左到右.
=
is parsed as right-associative, but order of evaluation is left-to-right.
所以:语句被解析为a[i] = (i = 9)
.然而,当 i
仍然是 0
.
So: The statement is parsed as a[i] = (i = 9)
. However, the expression i
in a[i]
is evaluated before the right hand side (i = 9
), when i
is still 0
.
这相当于:
int[] #0 = a;
int #1 = i;
int #2 = 9;
i = #2;
#0[#1] = #2;
这篇关于Java - 操作顺序 - 在一行中使用两个赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!