C++ reference aliasing and pre-decrement: what exact numbers are printed? #include <iostream.h> int main() { int x = 10; int &y = x; x = 25; y = 50; // x now 50 as well cout << x << " " << --y; // print x, then pre-decrement y (and thus x) return 0; }
-
AThe program will print the output 25 49.
-
BIt will result in a compile time error.
-
CThe program will print the output 50 50.
-
DThe program will print the output 49 49.
-
EThe program will print the output 50 49.
Answer
Correct Answer: The program will print the output 50 49.
Explanation
Introduction / Context: The item checks precise evaluation order when printing a referenced variable and then applying a pre-decrement to that same aliased object. Understanding that y is an alias of x is critical here.
Given Data / Assumptions:
- y is a reference bound to x.
- After assignments, x == 50 and y refers to x.
- cout << x occurs before evaluating --y in the chained insertion expressions.
Concept / Approach: In the chained output, operators are sequenced left-to-right. First, the current value of x (50) is sent to the stream. Next, --y is evaluated, which decrements the aliased object from 50 to 49, and that value (49) is inserted. Although x becomes 49 due to the aliasing, x was already printed as 50 prior to the decrement.
Step-by-Step Solution:
Bind y → x; set x = 25; then y = 50 → x becomes 50.cout << x → outputs 50.cout << " " → outputs a space.cout << --y → decrements to 49 and outputs 49.Verification / Alternative check: Replace --y with y-- and observe a different result (50 50) because y-- prints the old value before decrement; here we use pre-decrement.
Why Other Options Are Wrong:
- 25 49: ignores updates to 50.
- 50 50: would require post-decrement.
- 49 49: would require printing after the decrement for both positions.
- Compile time error: code is valid under classic headers.
Common Pitfalls: Assuming both outputs reflect the decremented value; confusing pre- and post-decrement semantics.
Final Answer: The program will print the output 50 49.