Java pre and post incrementing

I am having trouble understanding the following code.

int count = 0; for (int i = 0; i < 3; i++){ count += (count++); System.out.println("count = " + count); System.out.println("i = " + i); } 

I understand that the loop runs three times, pre-creating the following

 count = count + count count = 1 + count 

This means the following: count is initially 0:

 count = 0 + 0 count = 1 + 0 = 1 count = 1 + 1 = 2 count = 1 + 2 = 3 count = 3 + 3 = 6 count = 6 + 1 = 7 

The result is lower, and the number is counted as 0.

  count = 0 i = 0 count = 0 i = 1 count = 0 i = 2 

Can anyone explain this to me? Thanks

+4
source share
2 answers
 count += (count++); 

equivalently

 in tmp = count; // right hand side of += count = count + 1; // the count++ count = tmp + tmp; // executing count += tmp 

As you can see, count = count + 1 has no effect, since the value of count overwritten in the last line, and if count initially 0, then the result will obviously be count = 0 + 0 :-)

+3
source

The tangled part is the string -

 count+ = (count++); 

It effectively does it -

 count = count + ( count++ ); 

So, the value (count++) for the equation is 0, the post-increment occurs after, but then count gets the assigned value of 0, so the post-increment is discarded.

This happens 3 times.

+7
source

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


All Articles