In C, what is the output when assigning with post-increment on the same variable?
#include
int main()
{
int i = 3;
i = i++;
printf("%d
", i);
return 0;
}
-
A3
-
B4
-
C5
-
D6
-
EUndefined at compile time
Answer
Correct Answer: 3
Explanation
Introduction / Context:This classic C puzzle demonstrates how post-increment works when the same variable appears on both sides of the assignment. It is not undefined because there is only one modification of i in the full expression; the subtlety lies in the value produced by i++.
Given Data / Assumptions:
- i is initialized to 3.
- Post-increment returns the old value and then increments the variable.
- The assignment overwrites i with the result of the right-hand side.
Concept / Approach:For i = i++, the right-hand side evaluates to the original value (3). After producing that value, i is incremented to 4 as a side effect. Then the assignment stores the produced value (3) back into i, effectively discarding the increment.
Step-by-Step Solution:Initial i = 3.Evaluate i++: result value = 3; side effect schedules i → 4 before the next sequence point.Perform assignment i = (result 3): i becomes 3 again, clobbering the incremented value.printf prints 3.
Verification / Alternative check:Most compilers yield 3 for this construct in C (and many warn about confusing code). The C standard sequencing rules allow one modification; here the behavior is well-defined.
Why Other Options Are Wrong:(b), (c), (d) assume the increment survives the assignment, which it does not.
Common Pitfalls:Confusing this with undefined cases that modify and also read a variable twice without sequencing (e.g., printf("%d, %d", ++i, ++i)). Here, there is a single modification and the assignment overwrites the post-increment's increment.
Final Answer:3