This week's book giveaway is in the Design forum.We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!

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

colton peterson
Ranch Hand
Posts: 97
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: 34178
340
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
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: 34178
340
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
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
Thanks!