• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Why post increment i = i++ remains old i

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why

?
I seems it should be incremented, isn't it?
 
Marshal
Posts: 79178
377
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That is a classic pitfall. As the JLS (=Java® Language Specification) will tell you, the postfix operators make the value of the whole expreession equal to

the value of the variable before the new value is stored.

That means if you use =, all you achieve is setting that value of the variable back to what it was before the new value, soandboth print 123. We have an FAQ about that.
 
Saloon Keeper
Posts: 27763
196
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In other words, you increment i post getting its value. As opposed to pre getting the value.

Actually, what you'd usually code if you wanted a shorthand for simple incrementing is just "i++;" However, it's also useful in looping. A classic would be something that copies a string with all the "e"s removed:


Here, of course, you could simply code "ostr[j++]", but I've often coded loops where several items were all indexed by j in the same pass and wanted to make them all symmetrical:
 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This question is actually on our FAQ:

https://coderanch.com/wiki/659942/Post-Increment-Operator-Assignment
 
reply
    Bookmark Topic Watch Topic
  • New Topic