Using Increment in Expressions
You'll learn how prefix and postfix increment operators behave differently when embedded in larger expressions.
The Core Idea
You already know that ++ can appear before (prefix) or after (postfix) a variable. When you use these operators inside an expression—like an assignment or arithmetic operation—their timing makes a critical difference:
- Prefix (
++x): Increment happens first, then the new value is used in the expression - Postfix (
x++): The current value is used in the expression first, then increment happens
Think of it like ordering at a restaurant: prefix is "pay now, eat now" while postfix is "eat now, pay later."
Examples in Action
int a = 5;
int b = ++a; // a becomes 6, THEN b gets that value
// Result: a = 6, b = 6
int x = 5;
int y = x++; // y gets the current value 5, THEN x becomes 6
// Result: x = 6, y = 5
In arithmetic expressions:
int count = 10;
int result = count++ * 2; // 10 * 2 = 20, then count becomes 11
// Result: count = 11, result = 20
int num = 10;
int answer = ++num * 2; // num becomes 11 first, then 11 * 2 = 22
// Result: num = 11, answer = 22
The operator doesn't change what happens to the variable itself—it always increments. What changes is when the new value becomes visible to the surrounding expression.
Key Takeaway: Prefix ++x uses the new value immediately in expressions; postfix x++ uses the old value first, then increments afterward.