C++ (recursion with default arguments in a member function) — does the call terminate or loop forever, and what would be printed?
#include
class CuriousTab {
public:
void CuriousTab(int x = 15) {
x = x / 2;
if (x > 0)
CuriousTab();
else
cout << x % 2;
}
};
int main() {
CuriousTab objIB;
objIB.CuriousTab();
return 0;
}
Choose the correct behavior.
-
AThe program will display 1.
-
BThe program will display 2.
-
CThe program will display 15.
-
DThe program will go into an infinite loop.
-
EThe program will report error on compilation.
Answer
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
xand recurses withCuriousTab()(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: defaultx = 15 → x = 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.