#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.
Correct : 9
The key concept here is variable shadowing and scope in C.
func is called with i=9 and j=10 as parameters. The condition i < j checks 9 < 10 which is true, so we enter the if block.
Inside the if block, int i = 0 declares a brand new local variable also named i. This inner i is completely separate from the function parameter i — it simply shadows it within the if block''s scope. Any reference to i inside the if block now refers to this inner i, not the parameter.
The while loop runs with this inner i starting from 0. Each iteration increments the inner i by 1 and adds 2 to j. After 10 iterations the inner i reaches 10 and the loop exits. j becomes 30, but j is a local copy passed by value so this doesn''t affect anything outside.
Once the if block ends, the inner i goes out of scope and is destroyed. The printf statement that follows is outside the if block, so the name i now refers back to the original function parameter i, which was never touched — it is still 9.
Output: 9 ✓
Similar Questions
Total Unique Visitors