Consider the C function given below. int f(int j) { static int i = 50; int k;…

2014

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?

  1. A.

    The function returns 0 for all values of j.

  2. B.

    The function prints the string something for all values of j.

  3. C.

    The function returns 0 when j = 50.

  4. D.

    The function will exhaust the runtime stack or run into an infinite loop when j = 50.

Attempted by 142 students.

Show answer & explanation

Correct answer: D

Answer: The statement that the function will exhaust the runtime stack or run into an infinite loop when j = 50 is correct.

Key points:

  • The static variable i is initialized to 50 and retains that value across calls.

  • If j is not 50, the else branch executes and the function returns 0 immediately.

  • If j equals 50, the function prints "something" and then calls f(i), which is f(50) again.

  • Because the recursive call uses the same condition (j == 50) and there is no change that leads to a terminating case, the calls never stop normally. The program will either loop via repeated recursion (printing each time) until the stack is exhausted or otherwise crash.

  • Therefore the correct description of the function's behavior for j = 50 is infinite recursion leading to stack exhaustion, and the other statements (that it returns 0 for all j, that it prints for all j, or that it returns 0 when j = 50) are incorrect.

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir