C++ references with enum-backed ints: after chained increments and assignments, what are p, q, and z?\n\n#include <iostream.h>\nenum xyz { a, b, c };\nint main()\n{\n int x = a, y = b, z = c; // 0,1,2\n int &p = x, &q = y, &r = z;\n p = z;\n p = ++q;\n q = ++p;\n z = ++q + p++; \n cout << p << " " << q << " " << z;\n return 0;\n}

Difficulty: Medium

Correct Answer: 4 4 7

Explanation:


Introduction / Context:
This item probes careful sequencing of pre/post increment with references bound to ordinary integers initialized from enum constants. The emphasis is on precise order of evaluation and aliasing via references.


Given Data / Assumptions:

  • Initial values: x=0, y=1, z=2.
  • References: p=&x, q=&y, r=&z.


Concept / Approach:
Apply pre-increment (changes value, yields new value) and post-increment (yields old value, changes later) carefully. Assignment to p writes to x because p aliases x.


Step-by-Step Solution:
1) p = z; sets x = 2. 2) p = ++q; increments y to 2, then assigns 2 to x (still 2). 3) q = ++p; increments x to 3, assigns 3 to y. 4) z = ++q + p++;: pre-increment y to 4 (yields 4), use p++ as 3 then increment x to 4; sum is 7; assign to z. 5) Final values: x=4, y=4, z=7.


Verification / Alternative check:
Manually simulate with a small table of values after each statement to confirm the 4/4/7 state before the print.


Why Other Options Are Wrong:
Other tuples mismatch the post-increment of p or the pre-increment of q in the final expression.


Common Pitfalls:
Treating p++ as if it yields the incremented value; mixing up the aliasing of references; forgetting that z is updated last.


Final Answer:
4 4 7

More Questions from References

Discussion & Comments

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