Search code examples
javaassignment-operatorpost-increment

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;


I came across this line of code in java in nutshell book and I would like to know how compiler divide this code

a[i++] += 2;
a[i++] = a[i++] + 2;

Solution

  • 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

    I assume the order of evaluation should be as follows

    a[i++] = a[i++] + 2;
      ^      ^ ^
      1      3 2
             ----------
                 ^
                 4
    ------
      ^
      5
    --------------------
             ^
             6
    

    We can prove it by running this snippet

    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