tags:

views:

89

answers:

4

Possible Duplicate:
Difference between i++ and ++i in a loop?

Is there a difference between i++ and ++i ?

+2  A: 

i++ is postincrement and ++i is preincrement. The former allows you to use the value of i in an expression and then increments i at the end. The later increments i first and then allows you to use it. For example:

int prev_i=i++;

and

int next_i=++i;
Michael Goldshteyn
+1: naming as current_i would have been better though.
bjskishore123
+2  A: 

i++ increments i after the statement. ++i increments i before the statement is evaluated.

rerun
+2  A: 

Yes.

i++ is post-increment. It returns a copy of i and THEN increments the value of i.

++i is pre-increment. It increments i and THEN returns the value of i.

jcopenha
Wait wait wait. There is no ordering specified (this is where many novices go wrong and start believing that certain C++ expressions must have in practice well-defined effect). i++ is post-increment because "++" comes after (post) "i"; it increments the value of "i" and returns the original value of "i", in no particular order. :-) I know, that might sound crazy when you think of how to do it as an assignment. What you need to think of to really grok it is how the compiler might keep values around in registers and reuse them.
Alf P. Steinbach
@Alf P. Steinbach: Am I right in saying that your point has no practical effect unless you're doing things which are already thread-unsafe? Or can that come up somehow in a single-threaded environment?
Scott Stafford
@Scott: no to 1st, yes to 2nd. Consider `++x = 42`. When thinking about pre-increment as first incrementing and then producing a reference to x, how could this produce anything but x set to 42? Yet it is formally UB in C++98, since it modifies x twice between sequence points. It has to do with allowing the compiler to *assume* that there will at most be one change of x, and that x will not be both modified and used, so it can do things in registers and not worry about the final value, which ("right" or "wrong") it can just store to mem at the very end of the full-expression.
Alf P. Steinbach
+1  A: 

++c is pre-increment, so you increment the value before you use it, and c++ is post-increment, so you use the value then increment it.

int c;
c = 5;
cout << c++; // prints 5, then sets the value to 6
c = 5;
cout << ++c // sets the value to 6, then prints 6

So this can have implications in loops, etc. i.e.

int i;
for (i=0; i < 2; i++) cout << i; // prints 0, then 1
for (i=0; i < 2; ++i) cout << i; // prints 1, then 2

There are also potential performance implications. See this post for more information.

sidewaysmilk