In C, trace control flow with a global controlling a while loop and a recursive call to main(). What is printed?
#include
int i;
int fun();
int main()
{
while(i)
{
fun();
main();
}
printf("Hello
");
return 0;
}
int fun()
{
printf("Hi");
}
-
AHello
-
BHi Hello
-
CNo output
-
DInfinite loop
-
ECompile-time error due to recursion
Answer
Correct Answer: Hello
Explanation
Introduction / Context:This problem checks knowledge of default initialization for global variables in C and the effect on loop execution. It also includes a recursive call to main(), but that code path is guarded by the loop condition.
Given Data / Assumptions:
- Global int i is zero-initialized by default.
- while(i) executes only if i is nonzero.
- printf("Hello") executes after the loop.
Concept / Approach:In C, global (static storage duration) variables are initialized to 0 if not explicitly initialized. Therefore, i == 0 at program start. The while loop condition is false immediately, so the loop body (including fun() and the recursive call to main()) does not execute.
Step-by-Step Solution:Initialize i = 0 (by default).Evaluate while(i) → while(0) → condition false → skip body.Execute printf("Hello").Program terminates normally.
Verification / Alternative check:If you explicitly set i = 1 before the loop, the loop would run and call main() recursively, risking non-termination. Since i is 0, none of that occurs.
Why Other Options Are Wrong:“Hi Hello” would require entering the loop to print “Hi”. “No output” is false because “Hello” prints. “Infinite loop” would require i to be nonzero. There is no compile-time error for calling main recursively (though it is poor style).
Common Pitfalls:Assuming uninitialized globals are garbage; they are zeroed. Confusing this with local automatic variables that are indeterminate if not initialized.
Final Answer:Hello