What will be the output of the following C program?
C#include <stdio.h>
void main() {
static int x = 3;
x++;
if (x <= 5) {
printf("hi ");
main();
}
}
What will be the output of the following C program?
#include <stdio.h>
void main() {
static int x = 3;
x++;
if (x <= 5) {
printf("hi ");
main();
}
}Multiple Choice Options
- A
Runtime error
- B
hi
- C
Infinite hi
- D✓ Correct Option
hi hi
Detailed Technical Solution & Explanation
Let us trace the program execution step-by-step:
1. static int x = 3;: The static storage class ensures that x is allocated in the data segment and initialized only once before execution starts. Its state persists across recursive function calls.
2. First call to main():
- x++ increments x from 3 to 4.
- Condition if (x <= 5) () evaluates to true.
- Prints "hi " (1st output).
- Calls main() recursively.
3. Second call to main():
- static int x = 3; is skipped.
- x++ increments x from 4 to 5.
- Condition if (x <= 5) () evaluates to true.
- Prints "hi " (2nd output).
- Calls main() recursively.
4. Third call to main():
- x++ increments x from 5 to 6.
- Condition if (x <= 5) () evaluates to false.
- Recursion terminates and calls unwind.
Total output printed: "hi hi".
Option Analysis:
x is static, it increments on each call until .