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?
View worked solution
Answer: D
Let us trace the execution of the function when :
- The static variable
iis initialized to (this happens only once at the start of the program). - When we call
f(50), the parameterjis . - The condition
if (i == j)evaluates to50 == 50, which is true. - The function prints
"something"and then recursively callsk = f(i), which isf(50). - This recursive call
f(50)repeats the exact same sequence of steps, leading to an infinite recursion.
Because there is no base case to terminate this recursion when , the program will continuously push new activation records onto the call stack, eventually resulting in a stack overflow (exhausting the runtime stack).
Thus, option D is the correct choice.
Free practice · Your answers on this page are not saved.
