In C, analyze recursion via calling main() from main() and a toggled local variable. What is printed? #include<stdio.h> int main() { int i=1; if(!i) printf("CuriousTab,"); else { i=0; printf("C-Program"); main(); } return 0; }

Difficulty: Medium

Correct Answer: prints "C-Program" infinitely

Explanation:


Introduction / Context:
This program highlights recursion and automatic variable reinitialization. Each call to main() creates a new stack frame with a fresh automatic variable i, changing control flow compared to using a static or global variable.


Given Data / Assumptions:

  • Local automatic int i is initialized to 1 at the start of every main() invocation.
  • Branch uses if(!i). With i == 1, the else branch executes.
  • Else branch sets i = 0, prints "C-Program", and calls main() recursively.


Concept / Approach:
Because i is automatic, each recursive call resets i to 1, causing the else branch to run again. There is no base case to stop recursion, so the program repeatedly prints "C-Program" and recurses indefinitely (likely causing stack overflow eventually).


Step-by-Step Solution:
First call: i = 1 → else branch → print "C-Program" → call main().Second call: i reinitialized to 1 → else branch again → print "C-Program" → call main().This continues without termination.


Verification / Alternative check:
If i were static (static int i = 1;), the logic could eventually hit the if branch after setting i = 0 once. But as written, automatic reinitialization keeps the else branch active.


Why Other Options Are Wrong:
The string "CuriousTab," is never printed because the if branch never runs. There is no compile-time error from placing main() inside else; it compiles but is poor design. The program does not terminate after one print.


Common Pitfalls:
Assuming i maintains its modified value across recursive calls; with automatic storage, each call has its own i.


Final Answer:
prints "C-Program" infinitely

More Questions from Functions

Discussion & Comments

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