1

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

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

Community
  • 1
  • 1
rectangletangle
  • 50,393
  • 94
  • 205
  • 275

4 Answers4

3

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 value_of_i_before_increment=i++;

and

int value_of_i_after_increment=++i;
Michael Goldshteyn
  • 71,784
  • 24
  • 131
  • 181
2

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

rerun
  • 25,014
  • 6
  • 48
  • 78
2

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
  • 3,935
  • 1
  • 17
  • 15
  • 3
    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. – Cheers and hth. - Alf Oct 15 '10 at 03:51
  • @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 Oct 15 '10 at 03:56
  • 1
    @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. – Cheers and hth. - Alf Oct 15 '10 at 05:22
1

++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.

Community
  • 1
  • 1
Justin Force
  • 6,203
  • 5
  • 29
  • 39