In C++ (post-increment on a referenced argument), both parameters alias the same variable. Predict the printed pair. #include<iostream.h> class CuriousTab { int x, y; public: void SetValue(int &xx, int &yy) { x = xx++; y = yy; Display(); } void Display() { cout << x << " " << y; } }; int main() { int x = 10; int &y = x; CuriousTab objCuriousTab; objCuriousTab.SetValue(x, y); return 0; }

Difficulty: Easy

Correct Answer: The program will print the output 10 11.

Explanation:


Introduction / Context:
This tests post-increment behavior when two reference parameters alias the same object. The order of assignments matters: store x = xx++ first, then copy y = yy after the increment.


Given Data / Assumptions:

  • At call time, xx and yy both reference the same int x (initially 10).


Concept / Approach:
Post-increment returns the old value, then increments the underlying object. Because yy aliases the same object, reading yy after the increment observes the new value.


Step-by-Step Solution:

x (caller) starts at 10. x (member) = xx++ stores 10, then the caller variable becomes 11. y (member) = yy reads 11 (same aliased variable after increment). Display prints "10 11".


Verification / Alternative check:
Swapping the two assignment lines would change the observed pair because the timing of the increment differs.


Why Other Options Are Wrong:
They misread pre/post semantics or ignore that both references alias the same object.


Common Pitfalls:
Expecting both fields to be 11 due to misunderstanding of when the incremented value is used.


Final Answer:
The program will print the output 10 11.

More Questions from References

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion