In C++ (evaluation of function arguments with aliasing and a pre-increment), determine the printed triple. Consider potential aliasing effects between x and y (where y is a reference to x). #include<iostream.h> class CuriousTab { int a, b, c; public: void SetValue(int x, int y, int z) { a = x; b = y; c = z; } void Display() { cout << a << " " << b << " " << c; } }; int main() { CuriousTab objCuriousTab; int x = 2; int &y = x; y = 5; objCuriousTab.SetValue(x, ++y, x + y); objCuriousTab.Display(); return 0; }

Difficulty: Hard

Correct Answer: The program will print the output 6 6 12.

Explanation:


Introduction / Context:
This question highlights two advanced C++ concerns: (1) argument evaluation order is unspecified before C++17 (and unsequenced vs indeterminately sequenced rules have evolved), and (2) aliasing via int &y = x means both names refer to the same object. Many textbook compilers for such quizzes commonly evaluate left-to-right in practice, producing a particular observable result.


Given Data / Assumptions:

  • Initially x=2; then y=x; then y=5 sets x=5.
  • Call: SetValue(x, ++y, x + y) with y aliasing x.


Concept / Approach:
A prevalent evaluation path (and the intended answer in classic MCQs) first applies ++y (making x=6, y=6), and then computes x + y using the updated values, giving 12. The first argument observes the updated x as 6. The function stores (a, b, c) accordingly and Display prints them.


Step-by-Step Solution:

Before call: x=5, y=5. Evaluate ++y → x=6, y=6. Evaluate x (now 6) and x + y (6 + 6 = 12). Inside: a=6; b=6; c=12; Display prints "6 6 12".


Verification / Alternative check:
Different compilers or standards can yield different sequencing; however, competitive-programming/MCQ contexts typically expect the shown result. Using explicit temporaries or parentheses would remove ambiguity.


Why Other Options Are Wrong:
They assume older values (e.g., x=5) persist after ++y or mis-compute the sum.


Common Pitfalls:
Ignoring aliasing (x and y are the same) and relying on a guaranteed left-to-right evaluation across all standard versions.


Final Answer:
The program will print the output 6 6 12.

More Questions from References

Discussion & Comments

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