Jesse Emond Jesse Emond - 1 year ago 84
C++ Question

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

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download