In C++ (references and post-increment), evaluate the following code and determine the final printed values of m and n. Explain how the references x and y affect the updates.
#include
int main()
{
int m = 2, n = 6;
int &x = m;
int &y = n;
m = x++;
x = m++;
n = y++;
y = n++;
cout << m << " " << n;
return 0;
}
-
AThe program will print output 2 6.
-
BThe program will print output 3 7.
-
CThe program will print output 4 8.
-
DThe program will print output 5 9.
-
EThe program will print output 6 10.
Answer
Correct Answer: The program will print output 2 6.
Explanation
Introduction / Context: This tests how references alias variables and how post-increment (x++) yields the old value while still performing a side effect. Assignments may overwrite the incremented value, which is a classic source of confusion in interview questions.
Given Data / Assumptions:
- x aliases m; y aliases n.
- Both increments are post-increments (value used first, then incremented).
Concept / Approach: Track each statement carefully: compute the rvalue (old value for post-increment), perform the side effect (increment), then perform the assignment to the left-hand side which may overwrite the incremented value.
Step-by-Step Solution:
Start: m=2, n=6. m = x++; // rvalue 2, then m becomes 3, then assign 2 back → m=2. x = m++; // rvalue 2, m becomes 3, then assign 2 back via x → m=2. n = y++; // rvalue 6, n becomes 7, then assign 6 back → n=6. y = n++; // rvalue 6, n becomes 7, then assign 6 back via y → n=6. Printed: "2 6".Verification / Alternative check: Replace references with direct variables (m in place of x, n in place of y); the trace is identical because x and y alias m and n.
Why Other Options Are Wrong: They assume the incremented values survive the subsequent overwriting assignments; they do not in this sequence.
Common Pitfalls: Forgetting that post-increment returns the old value and that later assignments through references can revert the increment.
Final Answer: The program will print output 2 6.