Increment and Decrement Operators
What you'll learn: How ++ and -- operators modify variables and why their position matters.
The Core Idea
Increment (++) and decrement (--) operators provide shorthand for adding or subtracting 1 from a variable. They come in two forms:
- Prefix (
++xor--x): Modify the variable first, then use the new value in the expression - Postfix (
x++orx--): Use the current value in the expression first, then modify the variable
Think of it like getting a ticket at a deli counter. Prefix is like the machine incrementing before printing your number—you see the new number. Postfix is like receiving your current number, then the machine increments for the next person.
Example Behavior
x = 5
y = ++x // x becomes 6 first, then y gets 6
// Result: x=6, y=6
x = 5
y = x++ // y gets 5 first, then x becomes 6
// Result: x=6, y=5
Both forms ultimately change x by 1, but the timing of when that change is visible differs.
When Position Matters
If you use the operator in isolation (just x++ on its own line), prefix and postfix behave identically—the variable simply increases by 1. The difference only appears when you use the operator within a larger expression where the value is being assigned or evaluated.
count++ // Simple increment, prefix/postfix identical
total = count++ // Position matters here!
Key Takeaway: Prefix (++x) increments before evaluation; postfix (x++) increments after evaluation. When used alone, both simply add 1 to the variable.