• Post Reply Bookmark Topic Watch Topic
  • New Topic

Confused with Post increment operator  RSS feed

 
satish bejju
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Folks,

I have code like follows:


I thought at the end of for loop i will have the value 10.
But the value of i still 0 at the end of for loop. :s

Can you please explain why i value didnt change?
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It has to do with the order in which things happen in the i = i++ statement.

1. The current value of i is taken in preparation for carrying out the i = assignment.
2. The i variable is incremented
3. The value from step 1 is assigned to i - replacing the incremented value

Bill

 
satish bejju
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi William,

Thanks for quick reply

Yes i understood that the value got replaced with old one(i.e. Step 1).
But how as there are no assignment statements after increment..? :s

Let me put my understanding as follows:



first i got assigned (i=0), then its incremented, now its 1 which ideally should be available for next iteration.
But this is not happening in this case. :s

Satish Bejju
 
Liutauras Vilda
Marshal
Posts: 4665
320
BSD
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, satish,

This question arises quite ofthen, so CodeRanch got tutorial (<- link) for that.

Your example:
The problem why you don't get your expected result is, that each iteration you reset "i" to 0.

If you were try this, you'd get expected result:

Probably have a look at the tutorial above, it is clearer there.
 
satish bejju
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Liutauras Vilda,

Thanks for the link it cleared my confusion.

The answer is operator precedence will come into the picture.
Thanks a lot

Regards,
Satish
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have a look at our FAQ page: Post Increment Operator And Assignment
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!