Pre/Post increment operators and arrays

arrays, java

Solution

This:

int i= 0;
testArray[i++]= testArray[i++]+1;

is equivalent to:

int i= 0;
testArray[0]= testArray[1]+1;

which is equivalent to:

int i= 0;
testArray[0]= 20 + 1;

The post increment operator is increasing the value of the `int` causing it to pull the element in index 1 in the expression, that index is `==` 20. Obviously, the subsequent addition will make the value 21, which is then assigned to index 0 of the array.

To put it another way that relates to your description of the code. Your not using the index of the array that you assume you are.

Problem

I am trying out the following Java snippet: ``` int[] testArray={10,20,30,40}; int i= 0; testArray[i++]= testArray[i++]+1; System.out.println("The value of i: "+i); for(int i1=0;i1<testArray.length;i1++) { System.out.println(testArray[i1]); } ``` With i=0, the output values of the array are: `21, 20,30,40` I can't understand this output because the output should be: `10, 11, 30, 40` `testArray[0]+1` would be `11` and it would be then assigned to `testArray[1]` but this is not the case. Can anybody explain the output?

Original source