C++ (old iostream.h): trace the ternary, references, and side effects—what does this program output and why?
#include
int CuriousTabFunction(int m)
{
m *= m;
return ((10) * (m /= m));
}
int main()
{
int c = 9, *d = &c, e;
int &z = e;
e = CuriousTabFunction(c-- % 3 ? ++*d : (*d *= *d));
z = z + e / 10;
cout << c << " " << e;
return 0;
}
-
AIt will result in a compile time error.
-
BThe program will print the output 64 9.
-
CThe program will print the output 64 10.
-
DThe program will print the output 64 11.
-
EThe program will print the output 8 11.
Answer
Correct Answer: The program will print the output 64 11.
Explanation
Introduction / Context:
This problem checks understanding of the conditional (ternary) operator, pointer indirection, pre/post increment semantics, and references in C++. The code also includes a function that normalizes a nonzero number to 1 via m /= m.
Given Data / Assumptions:
- Old-style headers (
<iostream.h>) but otherwise standard semantics. - Initial
c = 9,dpoints toc. - Reference
zbound toe.
Concept / Approach: Evaluate the ternary condition carefully, track post-decrement and compound assignments, then propagate values through the function and the reference. Integer division and sequence points matter for the final value of e.
Step-by-Step Solution: 1) Condition: c-- % 3. The value used is 9 % 3 = 0, then c becomes 8. 2) False branch executes: (*d *= *d). Since d points to c (currently 8), c becomes 64. The argument to the function is 64. 3) In CuriousTabFunction: m *= m makes m = 4096; m /= m makes m = 1; returns 10 * 1 = 10. 4) Back in main: e = 10. Then, with z referencing e, z = z + e / 10 makes e = 10 + 1 = 11 (integer division). 5) Final print: c is 64; e is 11.
Verification / Alternative check: Replace the function with a direct expression returning 10 to confirm that only the normalization to 1 affects the result, not the squared size.
Why Other Options Are Wrong: Compile error: Code is valid in classic compilers. 64 9 / 64 10: Miss the final reference update by e/10. 8 11: Ignores that c was squared to 64.
Common Pitfalls: Forgetting that c-- uses 9 in the expression; misunderstanding reference aliasing; overlooking integer division.
Final Answer: 64 11