Question
Consider the C function given below:
int f(int j)
{
static int i = 50;
int k;
if (i == j)
{
printf("something");
k = f(i);
return 0;
}
else return 0;
}
Which one of the following is TRUE?
Official answer and solution
- Official answer
- D
- From
- Official GATE 2014 answer key
Solution
Trace the control flow and state of the static variable i when the function is invoked with j = 50.
-
Static Variable Semantics in C:
static int i = 50;is initialized once at program startup and retains its value across recursive calls.- Inside
f(int j),iis not modified by any assignment.
-
Execution with :
- On initial call
f(50):- The condition
if (i == j)evaluates , which isTRUE. - The string
"something"is printed. - The recursive call
k = f(i);is issued with argument .
- The condition
- On the recursive call
f(50):- Parameter .
- Static variable remains .
i == jis againTRUE, prints"something", and callsf(50)again.
- On initial call
-
Resulting Behavior:
- Each recursive call creates a new stack frame on the call stack.
- Because the recursion has no terminating condition when , it recurses infinitely until memory allocated for the call stack is exhausted, triggering a stack overflow crash.
- Therefore, the function will exhaust the runtime stack or run into an infinite loop when (Option D).
Final answer
D
Common trap
Assuming that return 0 is reached; the return statement is placed after the recursive call k = f(i), which never returns.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2014 Computer Science and Information Technology (CS) Session 2
- Question
- 52 of 65, printed as CS Q.42
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.