Increment and Decrement: Pre vs. Post
You already know how to add 1 to a variable:
count += 1; // same as count = count + 1Adding 1 (or subtracting 1) is so common that C++ gives it an even shorter form:
count++; // same as count += 1This may look like a small convenience with nothing to think about. But C++ actually gives you two versions of this shorthand, count++ and ++count, and they are not interchangeable. Used as a standalone statement they behave identically, but the moment you use them inside a larger expression, they can give you different values.
Post-increment: use first, then change
count++ is called post-increment because the variable is incremented only after its value has been read.
On line 5, tickets_sold is incremented after its value has been assigned to old_total. That’s why old_total ends up holding 10 (the value from before the increment), while tickets_sold ends up with 11.
Pre-increment: change first, then use
++count is called pre-increment because the increment happens before the value gets used.
Both variables end up holding 11, because tickets_sold was incremented first, and that’s the value updated_total received.
That’s the whole distinction: pre-increment evaluates to the updated value, post-increment to the old one, even though the variable is incremented either way.
Same pattern with decrements
Decrement, with count-- and --count, follows the same pre/post distinction:
Post-increment’s extra step
Under the hood, post-increment makes a copy of the value before changing the variable. So it does one extra copying step that pre-increment skips.
For a plain int, that copying cost is negligible, so in practice it makes no real difference in performance which operator you use in a standalone statement. Still, pre-increment does strictly less work, which is why many experienced C++ programmers default to it out of habit.
A problem with multiple increments in an expression
It’s tempting to pack an increment into a bigger expression, like:
int x = 5;int result = x++ + ++x;The variable x is being modified twice in this one expression (by x++ and by ++x), but the language standard does not guarantee which of those two modifications happens first. So different compilers can produce different results. The rule of thumb is to never read and modify the same variable more than once in a single expression. Instead, split it into separate statements that have a clear intent:
int x = 5;int a = x++;int b = ++x;int result = a + b;Checkpoint
Given this code, what gets printed?
int x = 5;
int result = 5 + x++ * 2;
std::cout << result;