In C++ (old-style headers, iostream.h), analyze pointer and reference increments and predict the output.\n\n#include <iostream.h>\nint main()\n{\n int x = 10, y = 20;\n int *ptr = &x;\n int &ref = y;\n\n *ptr++; // increments ptr (postfix), dereferenced value discarded; x unchanged\n ref++; // increments y\n\n cout << x << " " << y;\n return 0;\n}\n

Difficulty: Easy

Correct Answer: The program will print the output 10 21.

Explanation:


Introduction / Context:
This problem tests C++ operator precedence with pointers, the difference between postfix ++ on a pointer versus on a referenced variable, and how these affect the underlying integers when using the classic iostream.h style program.


Given Data / Assumptions:

  • x = 10, y = 20 at start.
  • ptr points to x; ref aliases y.
  • Expression *ptr++; uses postfix ++ on the pointer.
  • ref++; increments the referenced integer y.


Concept / Approach:
In the expression *ptr++, postfix ++ has higher precedence than *. Therefore *ptr++ is parsed as *(ptr++). The pointer is advanced to the next int, and the dereferenced value (from the old address) is evaluated and discarded. No write occurs to x, so x remains 10. By contrast, ref++ increments the aliased object (y) by 1, so y becomes 21.


Step-by-Step Solution:

Initial: x = 10, y = 20.*ptr++ → increments ptr only; x unchanged.ref++ → y becomes 21.cout prints x then y → 10 21.


Verification / Alternative check:
Rewriting as *(ptr++); ref++; clarifies that the first statement has no side-effect on x. If the intent were to increment x, one would write (*ptr)++.


Why Other Options Are Wrong:

  • 10 20: ignores the increment via ref++.
  • 11 20 / 11 21: would require (*ptr)++ to mutate x, which is not present.
  • Compile time error: the code is valid under classic headers.


Common Pitfalls:
Misreading *ptr++ as (*ptr)++; forgetting postfix ++ binds tighter than *; assuming pointer increment changes the pointee.


Final Answer:
The program will print the output 10 21.

More Questions from References

Discussion & Comments

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