Incrementing in C++ - When to use x++ or ++x?

Jesse Emond picture Jesse Emond · Nov 28, 2009 · Viewed 199k times · Source

I'm currently learning C++ and I've learned about the incrementation a while ago. I know that you can use "++x" to make the incrementation before and "x++" to do it after.

Still, I really don't know when to use either of the two... I've never really used "++x" and things always worked fine so far - so, when should I use it?

Example: In a for loop, when is it preferable to use "++x"?

Also, could someone explain exactly how the different incrementations (or decrementations) work? I would really appreciate it.

Answer

Oliver Friedrich picture Oliver Friedrich · Nov 28, 2009

It's not a question of preference, but of logic.

x++ increments the value of variable x after processing the current statement.

++x increments the value of variable x before processing the current statement.

So just decide on the logic you write.

x += ++i will increment i and add i+1 to x. x += i++ will add i to x, then increment i.