1.3Increment, decrement and side effects
The idea
x++ hands you the old value and then adds 1. ++x adds 1 first and hands you the new value. Changing a variable twice in one expression is undefined.
Think of it like this: Post-increment is like reading the date off a calendar and then turning the page; pre-increment turns the page first.
Why it exists
Side effects inside conditions and indexes (i++ < 3, a[i++]) are the standard source of off-by-one output puzzles.
How it works
- y = x++: copy x into y, then x = x + 1.
- z = ++x: x = x + 1, then copy x into z.
- In a loop condition like i++ < 3 the comparison uses the old i, but the body already sees the new one.
- If a variable is both modified and used (or modified twice) between sequence points, stop: it is undefined.
Worked example: while (i++ < 3)
i = 0: test 0 < 3 true, then i = 1, body adds 1. i = 1: test true, i = 2, adds 2. i = 2: test true, i = 3, adds 3. i = 3: test 3 < 3 false, but i still becomes 4. So n = 6 and i = 4 at the end.
Now play with it
- →Run x++ versus ++x and watch x, y, z change line by line.
- →Open the undefined tab: note that no one answer is "correct".
Post-increment gives the OLD value; pre-increment gives the NEW value. Step through and watch x, y and z.
1#include <stdio.h>2int main() {3 int x = 5, y, z;4 y = x++;5 z = ++x;6 printf("%d %d %d\n", x, y, z);7 return 0;8}
The gold line is the statement about to run.
Call stack (top first)
Output
Check yourself
int x = 5; int y = x++ + 1; What are x and y?
Exam notes (the dense version)
x++ gives the old value and then adds 1; ++x adds 1 and gives the new value. Changing the same variable twice, or reading it while changing it, between two sequence points (as in i = i++ + ++i or a[i] = i++) is undefined behaviour. Sequence points exist at ;, &&, ||, ?:, the comma operator and before a function call.
Previous year questions: Types, Operators & Expressions (2)
PYQs are grouped by topic, so this is the full set for Types, Operators & Expressions; try the ones that match this subtopic. Open all 2 on the topic page.