Question

Can anyone explain me why such call doesn't increment my i value ?

int i = 0;
list.get(7 + (i = i++));
list.get(7 + (i = i++));

it leaves i=0 instead of increment by one at least such that in the second call it is 1.

Was it helpful?

Solution

i = i++ is like doing:

int old_i = i; 
i = i + 1;
i = old_i; 

What is actually happening is that the value of i++ is the value of i before the increment happens, then i will get the value of.. i.

In one line i++ will use the old value of i and then it will increment it.

OTHER TIPS

i = i++ assigns first and increments second

heres what the execution essentially looks like:

list.get(7 + (i = i)); //list.get(7);
i = i + 1; //i = 1
list.get(7 + (i = i); //list.get(8);
i = i + 1; //i = 2

++i will increment the variable first and assign second

i = i++ means that i will be assigned the old value of i which then will be incremented by 1. If you want to really increment your value, you should write either:

int i = 0;
list.get(7 + (i++));
list.get(7 + (i++));

or:

int i = 0;
list.get(7 + (i+1));
list.get(7 + (i+2));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top