C++ (recursion with default arguments in a member function) — does the call terminate or loop forever, and what would be printed?\n\n#include<iostream.h>\nclass CuriousTab {\npublic:\n void CuriousTab(int x = 15) {\n x = x / 2;\n if (x > 0)\n CuriousTab();\n else\n cout << x % 2;\n }\n};\nint main() {\n CuriousTab objIB;\n objIB.CuriousTab();\n return 0;\n}\n\nChoose the correct behavior.

Difficulty: Medium

Correct Answer: The program will go into an infinite loop.

Explanation:


Introduction / Context:
This snippet highlights a common trap: recursion with a default parameter that is re-applied at each call. Although the body halves a variable and seems to move toward a base case, the recursive call does not pass that new value along, so the base case is never reached.


Given Data / Assumptions:

  • Member function signature: void CuriousTab(int x = 15).
  • Body halves x and recurses with CuriousTab() (no argument).
  • Default argument value 15 is used whenever the call omits the parameter.


Concept / Approach:
Each recursive call with no explicit argument uses the default, setting x to 15 again, then halving to 7, then recursing again with the default, and so on. The halved value is never propagated into the next call, so the condition x > 0 remains true on every activation until the call stack overflows or the runtime aborts, i.e., it behaves like an infinite loop (non-terminating recursion).


Step-by-Step Solution:

Initial call: default x = 15x = 7.Recursive call with no argument applies default again: x = 15 → 7.This process repeats indefinitely; the else branch is never reached.


Verification / Alternative check:
Fix by passing the updated value: CuriousTab(x). Then the sequence 15 → 7 → 3 → 1 → 0 will terminate, printing 0 % 2 = 0.


Why Other Options Are Wrong:

  • Printing 1, 2, or 15 presumes termination; it does not terminate.
  • Compilation error does not occur; the code is syntactically valid.


Common Pitfalls:
Confusing default arguments with persistent state, and forgetting that defaults are reapplied at each call when the argument is omitted.


Final Answer:
The program will go into an infinite loop.

More Questions from Functions

Discussion & Comments

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