Unexpected output for multiple array assignment

Consider

int b = 2;

int[] a = new int[4];

a[a[b]] = a[b] = b = 2;

for (int i = 0; i <= 3; i++)
{
    System.out.println(a[i]);
}

Output signal

2
0
2
0

I expected to a[0]be zero.

+4
source share
6 answers

Excerpt from JLS 15.26.1. Simple assignment operator =

If the left operand is an array access expression (§15.13), it may be enclosed in one or more pairs of parentheses, and then:

First, an array reference subexpression of the left operand is evaluated as an array access expression. If this evaluation completes abruptly, then the assignment expression abruptly terminates for the same reason; index subexpression (access expression from the left array of operands), and the right operand is not evaluated, and no assignment is performed.

, a[a[b]] a[0] . a[0] = a[b] = b = 2, .

. http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.1

+2

a[a[b]] , a[0], 2.

b = 2, a[b] = 0 so a[a[b]] = 2
+1

a[a[b]] = a[b]=b=2,

a[a[b]] i.e, a[a[2]] -> a[0] //initially the value of a[2] will be 0

,

a[0]=a[2]=b=2;

2 0 2 0
+1

, java: Java?

, = . java , a[a[b]] . a[b] 0.

+1

, a[a[b]] = a[b]=b=2; :

a[a[b]]: b 2, a[2] 0, a[a[2]] - a[0].

a[a[b]] = a[b]=b=2; a[0] = a[b]=b=2;

a[0] = a[2] =2;, a[2] 2 a[0] a[2]

0

,

a [a [b]] = a [b] = b = 2;

from right to left and expecting the array and b to be reevaluated at every step, when it actually seems that a and b are frozen during the assignment. Consider the equivalent code:

1) int b = 2;          

//array initialized to 0
2) int[] a= new int[4]; // 0 0 0 0   

// at this point a[b] is a[2] = 0, therefore  below a[a[b]]=2 is equivalent to  a[0]=2
3) a[a[b]] = 2          // 2 0 0 0    

// the same: a[b] = 2 is equivalent to a[2] = 2  -note that the arrays are zero based
4) a[b]= 2              // 2 0 2 0

5) b=2;
0
source

Source: https://habr.com/ru/post/1533317/


All Articles