Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

data[i++] = data[i++] * 2 result surprised me

I just declare the data array

data = {0, 1, 2, 3, 4},  i = 1;  
data[i++] = data[i++] * 2;

I test in Java and Javascript, the results both are

{0, 4, 2, 3, 4}

it's too strange to me, I think at first

data[i++] * 2, data[1] * 2 = 2,

then i becomes 2, then data[2] = 2 and i become 3. So result should be {0, 1, 2, 3, 4}.

Could someone know the reason of this result?

like image 933
regrecall Avatar asked Feb 20 '26 09:02

regrecall


1 Answers

From the Java Language Specification at http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.1

If the left-hand operand is an array access expression (§15.13), 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.

  • Otherwise, 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.

In other words, the array index on the left hand side MUST be evaluated before the right hand side, to conform to the Java Language Specification.

This means that you'll be assigning into data[1], and the value that you assign will be data[2] * 2.

If you're asking about Javascript though, all I can suggest is that the makers of Javascript wanted to make the result match the result from Java.

like image 164
Dawood ibn Kareem Avatar answered Feb 22 '26 23:02

Dawood ibn Kareem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!