Undefined behavior: i = i++
What you'll learn: Why trying to change the same variable twice in a single expression can cause your program to behave unpredictably.
The Mystery of the Single Line
In C, it is tempting to try and be "clever" by combining multiple operations into one line. You might look at the expression i = i++ and assume the logic is straightforward: take the current value of i, assign it to itself, and then increment it. Or perhaps it increments first and then assigns?
The truth is much more chaotic. In the C standard, this is known as Undefined Behavior (UB).
The Analogy: Two Bosses, One Assistant
Imagine you are an assistant (the CPU) and you have two bosses (the increment operator and the assignment operator). Both bosses give you a task to perform on the same filing cabinet (i) at the same time:
- Boss A (Assignment): "Overwrite the folder
iwith the value 5." - Boss B (Increment): "Add 1 to the folder
i."
If Boss A and Boss B don’t coordinate, you don't know which task to finish first. If you increment and then overwrite, the increment is lost. If you overwrite and then increment, the value changes twice. In C, the "Sequence Point" (the moment where all side effects must be finished) only happens at the semicolon. Between the start of the line and that semicolon, the compiler is allowed to perform those two tasks in any order it finds most efficient.
Why This is Dangerous
When behavior is "undefined," the C compiler is not required to be consistent. On your laptop, i = i++ might result in i staying the same. On a different compiler or a smartphone, it might result in i increasing. It could even result in a crash.
#include <stdio.h>
int main() {
int i = 5;
// DANGEROUS: Modifying 'i' twice in one expression
i = i++;
// The result is unpredictable!
printf("Value of i: %d\n", i);
return 0;
}
The Golden Rule
To keep your code safe and readable, follow this rule: A variable should be modified at most once in a single expression. If you want to increment a value and assign it, do it in two separate steps. Clarity always beats "clever" code that might break on a different computer.
Key takeaway
Never modify the same variable more than once between sequence points (like semicolons), as the resulting value is unpredictable and varies between compilers.