In modern C++ (iostream), evaluate references bound to the same int and an enum-to-int assignment. What does this program print and why? #include<iostream> enum curioustab { a = 1, b, c }; int main() { int x = c; // x = 3 int &y = x; int &z = x; y = b; // x becomes 2 std::cout << z--; // print then decrement return 0; }

Difficulty: Easy

Correct Answer: The program will print the output 2.

Explanation:


Introduction / Context:
This problem mixes enum-to-int initialization, reference aliasing, and post-decrement printing behavior. All references y and z alias the same underlying int x.


Given Data / Assumptions:

  • Enum values: a=1, b=2, c=3; x starts as 3.
  • y and z both reference x.
  • y=b sets x to 2 before the print.


Concept / Approach:
With aliasing, assignments via any reference affect x. The expression z-- is post-decrement, so it prints the old value of x (which is 2) and only then decrements x to 1.


Step-by-Step Solution:

Initialize: x=3. y=b → x=2. std::cout << z-- prints 2, then x becomes 1.


Verification / Alternative check:
Replacing z-- with --z would print 1 immediately because pre-decrement decrements before yielding the value.


Why Other Options Are Wrong:
1 or 3 would require different timing of decrement or no prior assignment; compile error does not apply.


Common Pitfalls:
Forgetting that all references alias the same int and misapplying pre/post decrement semantics.


Final Answer:
The program will print the output 2.

More Questions from References

Discussion & Comments

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