Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java pre and post incrementing

I am having trouble understanding the following code block.

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

My understanding is that the loop runs three times preforming the following

count = count + count
count = 1 + count

This translates to the following as count initially is 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 output is below, and count is printed as 0.

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

Could someone explain this to me? Thanks

like image 323
pillsdoughboy Avatar asked Jan 17 '23 04:01

pillsdoughboy


1 Answers

The confusing part is this line --

count+ = (count++);

This effectively is doing this --

count = count + ( count++ );

So, the value of (count++) for the equation is 0, the post-increment happens after, but then count gets assigned a 0, so the post-increment is thrown away.

This happens 3 times.

like image 62
Kal Avatar answered Jan 25 '23 22:01

Kal