C++ reference pre-decrement through an alias: what is printed? #include<iostream.h> int main() { int x = 80; int &y = x; x++; cout << x << " " << --y; return 0; }

Difficulty: Easy

Correct Answer: The program will print the output 81 80.

Explanation:

Introduction / Context: This question verifies understanding of pre-decrement applied via a reference. Because y aliases x, changing y changes x immediately.

Given Data / Assumptions:

  • Initial x=80, then x++ gives x=81.
  • y refers to the same object as x.

Concept / Approach: Pre-decrement (--y) decrements first and yields the decremented value. Since y aliases x, --y reduces x to 80 and yields 80.

Step-by-Step Solution: 1) After x++, x is 81. 2) First printed value: x is 81. 3) --y decrements the same object to 80 and yields 80; second printed value is 80. 4) Final state: x=80.

Verification / Alternative check: If --x were used instead, the second printed value would still be 80, showing the alias equivalence.

Why Other Options Are Wrong: 80 80 ignores the prior increment; 81 81 misapplies pre-decrement; compile error is inapplicable.

Common Pitfalls: Forgetting that y is an alias for x and that pre-decrement changes the value before yielding it.

Final Answer: 81 80

More Questions from References

Discussion & Comments

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