Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pre/Post increment operators and arrays

Tags:

java

arrays

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?

like image 770
user1107888 Avatar asked Oct 18 '25 14:10

user1107888


2 Answers

In the following assignment:

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

First the value of i++ is evaluated, which comes out to be 0. Then the value of i is incremented. So, the value of i has become 1 before the RHS starts evaluating. So, basically, the above expression is equivalent to:

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

and after the above expression, the value of i would be 2. If you however change the expression to:

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

.. you will get the expected result.

like image 148
Rohit Jain Avatar answered Oct 20 '25 03:10

Rohit Jain


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.

like image 34
Kevin Bowersox Avatar answered Oct 20 '25 03:10

Kevin Bowersox



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!