Increment & Decrement
Operators in C++
Master ++ and -- operators: understand the critical difference between prefix and postfix behavior and write cleaner, bug-free code.
What Are Increment & Decrement Operators?
In C++, the increment operator (++) adds 1 to a variable, and the decrement operator (--) subtracts 1. They are shorthand for common operations you use in loops, counters, and pointer arithmetic.
Why Do They Matter?
Two Forms: Prefix vs Postfix
Both ++ and -- come in two flavors. The difference is when the value changes relative to when it is used in an expression.
The Core Rule
Same Rules for Decrement
The -- operator follows the exact same prefix/postfix logic, but subtracts 1 instead of adding 1.
Key Distinction: Standalone vs In Expressions
When used as a standalone statement, prefix and postfix are identical. The difference only matters when the operator is inside a larger expression.
How to Apply: Step by Step
Example 1: Prefix Increment
Example 2: Postfix Increment
Example 3: Combined in a Loop
In a for loop's update expression, \( \texttt{i++} \) and \( \texttt{++i} \) produce the same loop behavior because the result of the expression is discarded: only the side effect (incrementing i) matters.
Example 4: Tricky Multi-Use
Golden rule: Never use ++ or -- on the same variable more than once in a single statement. Split it into separate lines instead.
Example 5: Decrement in Action
Common Mistakes
Summary Comparison Table
| Prefix (++x / --x) | Postfix (x++ / x--) | |
|---|---|---|
| Order of Operations | Change first, then use | Use first, then change |
| Expression Value | New value | Old value |
| Variable After | Incremented / decremented | Incremented / decremented |
| Standalone Use | Identical result | Identical result |
| Performance | No temp copy needed | May create temp copy |
| Recommended for Loops | ✓ Preferred | Works but less idiomatic |
Question 1 of 5
If \( \texttt{int x = 10;} \) and \( \texttt{int y = ++x;} \), what are the values of \(x\) and \(y\)?
Question 2 of 5
If \( \texttt{int x = 10;} \) and \( \texttt{int y = x++;} \), what are the values of \(x\) and \(y\)?
Question 3 of 5
Given \( \texttt{int n = 5;} \), what does \( \texttt{--n} \) evaluate to, and what is \(n\) afterward?
Question 4 of 5
In a for loop, does it matter whether you write \( \texttt{i++} \) or \( \texttt{++i} \) as the update expression?
Question 5 of 5
What is wrong with this code?
\( \texttt{int x = 3; int y = x++ + ++x;} \)