Question:medium

Consider the following program in C:
#include <stdio.h>

void func(int i, int j) {
  if (i < j) {
    int i = 0;
    while (i < 10) {
      j += 2;
      i++;
    }
  }
  printf("%d", i);
}

int main() {
  int i = 9, j = 10;
  func(i, j);
  return 0;
}
The output of the program is __________. (answer in integer)
Note: Assume that the program compiles and runs successfully.

Show Hint

The declaration \(int\ i = 0;\) inside the if block creates a new variable that only shadows the outer parameter \(i\) within that block. Once the block ends, that shadow variable disappears and the original parameter value reappears unchanged for the final printf.
Updated On: Jul 22, 2026
Show Solution

Correct Answer: 9

Solution and Explanation

Track this with a simple table of which variable binding is active at each point in the program, since the whole trick is scope, not arithmetic.
  • On entry to func, there is one binding for $i$, the parameter, holding the value 9, and one binding for $j$, the parameter, holding the value 10.
  • The condition $9 < 10$ is true, so we enter the if block. The very first line inside that block, $int\ i = 0$, creates a second, separate binding for the name $i$ that exists only for the lifetime of this block. From here until the block's closing brace, the name $i$ resolves to this new binding, not the parameter.
  • The while loop uses this new, block-scoped $i$ as its counter, running it from 0 up to 10 in ten steps. Each step also adds 2 to $j$, since $j$ has only one binding throughout the function, so $j$ ends the loop at $10 + 20 = 30$. The block-scoped $i$ ends at 10, but that value is discarded the moment the block ends.
  • Once execution passes the block's closing brace, the block-scoped binding for $i$ is destroyed, and the name $i$ reverts to referring to the original parameter binding, which still holds 9, because that parameter was never written to; only its shadow was.
  • The final $printf$ statement sits outside the if block, so it prints whatever the currently active $i$ binding holds, which is the parameter's value, 9.
So the program outputs 9.
$$\boxed{9}$$
Was this answer helpful?
0

Top Questions on C Programming: Scope and Variable Shadowing


Questions Asked in GATE CS exam