Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning and incrementing a value during method call

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.

like image 967
xwhyz Avatar asked Jul 24 '13 15:07

xwhyz


2 Answers

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.

like image 107
Maroun Avatar answered Nov 15 '22 08:11

Maroun


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

like image 32
mistahenry Avatar answered Nov 15 '22 08:11

mistahenry