C++ reference semantics (post-increment in stream): what exact output appears and why? #include<iostream.h> int main() { int x = 10; int &y = x; x++; cout << x << " " << y++; return 0; }

Difficulty: Easy

Correct Answer: 11 11

Explanation:

Introduction / Context: This problem ensures you understand references and post-increment when used inside a streaming expression. Because y is a reference to x, y++ modifies x after yielding its current value.

Given Data / Assumptions:

  • Start: x=10.
  • int &y = x; so y aliases x.
  • Then x++; makes x=11.

Concept / Approach: Post-increment (y++) yields the old value of y (which equals the current x) and then increments the object. Streaming prints values in order, using the produced value of each subexpression.

Step-by-Step Solution: 1) After x++, x becomes 11. 2) cout << x prints 11 first. 3) y++ yields 11 (the current value), then increments the same underlying x to 12. 4) The output tokens are thus 11 and 11; the final state is x=12.

Verification / Alternative check: Replace y with x; x++ in the stream shows identical printed result but changes the final state after printing.

Why Other Options Are Wrong: Options showing 12 as the first number ignore that increment happened before printing; options showing 12 as the second number forget that post-increment prints the old value.

Common Pitfalls: Confusing pre- vs post-increment result value; forgetting that y and x are the same object.

Final Answer: 11 11

More Questions from References

Discussion & Comments

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