Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

post/pre-increment/decrement A.K.A. ++ - -

 
colton peterson
Ranch Hand
Posts: 97
Linux Python VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the difference between i++ and ++i?

if i = 1; then wouldn't the both make I equal 2?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34071
331
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes and if you have them as a command by themselves, they work the same. If you have them in a command that also does something else, you get different results because they increment/decrement at different times.

Try running the following code:


They give different results because they increment at different times.
 
colton peterson
Ranch Hand
Posts: 97
Linux Python VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it said

1
2

process complete

so i++ returns the value and then increments
and ++i increments the value then returns

right?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34071
331
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by colton peterson:
so i++ returns the value and then increments
and ++i increments the value then returns

Right!
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by colton peterson:

so i++ returns the value and then increments
and ++i increments the value then returns


Not exactly.

Both actually increment the value of i *first*, and then return. The difference is that i++ returns the value i had before the increment, ++i returns the value i has after the increment.

That is why

i = i++;

doesn't change the value of i at all. Or more precisely, it first increments the value of i, and then sets it back to the old value.
 
colton peterson
Ranch Hand
Posts: 97
Linux Python VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic