C++ reference pre-decrement through an alias: what is printed?
#include
int main()
{
int x = 80;
int &y = x;
x++;
cout << x << " " << --y;
return 0;
}
-
AThe program will print the output 80 80.
-
BThe program will print the output 81 80.
-
CThe program will print the output 81 81.
-
DIt will result in a compile time error.
-
EThe program will print the output 82 81.
Answer
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, thenx++givesx=81. yrefers to the same object asx.
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