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

Viewed 245945

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.

12 Answers

If count{5};

If you use ++count it will be process beforethe statement

total = --count +6;

Total will be equal to 10

If you use count++ it will be process after the statement

total = count-- +6;

Total will be equal to 11

You asked for an example:

This (order is a std::vector) will crash for i == order.size()-1 on the order[i].size() access:

while(i++ < order.size() && order[i].size() > currLvl);

This will not crash at order[i].size(), as i will be incremented, checked and the loop will be exited:

while(++i < order.size() && order[i].size() > currLvl);
Related