Assignment and increase of value during method call

Can someone explain to me why such a call does not increase the value of i ?

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

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

+6
source share
3 answers

i = i++ - do this:

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

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

In one line of i++ , the old value of i will be used, and then it will increase it.

+7
source

i = i++ assigns the first and increments to the second

Here's what the performance 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 first increment the variable and assign the second

+4
source

i = i++ means that i will be assigned the old value i , which will then be increased by 1. If you want to really increase your value, you must 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)); 
+1
source

Source: https://habr.com/ru/post/950200/


All Articles