in Programming in C retagged by
337 views
6 votes
6 votes

What will be the output of the program below-

int i = 1;
void my_extern1(void);
void my_extern2(void);

int main() {
    int count = 0;
    
    while (i++<5) {
        static int i = 3;
        i++;
        count +=i;
        my_extern1();
    }
    printf("%d", count);
}

void my_extern1(){
    extern int i;
    if(i++ > 0) my_extern2();
}

void my_extern2(){
    extern int i;
    if (i++ < 3) my_extern1();
}
  1. Infinite recursion
  2. $9$
  3. $4$
  4. $5$
in Programming in C retagged by
337 views

1 Answer

0 votes
0 votes
int i = 1 is declared in global scope . when the while loop enters the global i is incremented by 1 and becomes 2 and in the while block static int i is created and initialized to 3  and then incremented by 1 which becomes 4 and on adding to count , count becomes 4 . Then my_extern1 is called which satisfies the if condition and  global i is incremented by 1 which becomes 3 and my_extern2 is called since 3 is not less than 3 the control returns to my_extern1 function after incrementing global i by 1 which becomes 4 and since 4 is less than 5 while loop again runs and after than global i is incremented to 5 and static i is incremented by 1 which becomes 5 and then added to count which becomes 9(4+5). and myextern1 is called from but myextern1 will not call myextern2 because condition is not satisfied. so control returns to main function and while loop condition is checked and since the condition is not satisfied the loop breaks and 9 is printed.

So the correct option is B because count value will be 9 .

2 Comments

@abir_banerjee

myextern1 is called from but myextern1 will not call myextern2 because condition is not satisfied.

This is not correct bcz when myextern1 is called... that tym value of global i is 5.

→ (5>0) this is true. After that, i is incremented by 1. It becomes 6. Then myextern2() is called.

→ (6<3) this is false. After i incremented by 1. It becomes 7. Condition fails myextern2() return and after that myextern1() return.

→ Again when the while loop has been checked, the time value of i (global) is 7. (7<5) false, and i becomes 8.

So, the value of global i is 8, and the value of static i is 5.

2
2

@abir_banerjee Your answer needs correction.

Final Values:-

Global $i = 8$

Static $i = 5$

Count $ = 9$

0
0
Answer:

Related questions