2,451 views

1 Answer

Best answer
5 votes
5 votes

Output will be 5.

If the assingment $i=1$ was not there then output would be 7.

Notice that the statement static int i; initializes $i$ to $0$.

Here i is initialized to $0$. In first rec call value of $i$ is $0$ (before the assignment $i=1;$)

In second rec call, initially value of i is 2, but after assignment it becomes 1 again. It's nothing unusual. Just normal assignment.

In 3rd call, initially value of i is 2 (since last modified value of $i$ was $2$), but after assignment it becomes 1 again.

So static variable is retaining its value across function calls. It's just that we're reassigning it to 1 in the assignment $i = 1.$

selected by

Related questions

1 votes
1 votes
3 answers
1
jverma asked May 23, 2022
1,029 views
#include <stdio.h>int f(int n){ static int r = 0; if (n <= 0) return 1; r=n; return f(n-1) + r;}int main() { printf("output is %d", f(5)); return 0;}Ou...
0 votes
0 votes
1 answer
2
srestha asked Nov 18, 2018
1,253 views
Is it static declaration or static assignment?int main() { int x=20; static int y=x; if(x==y) printf("Equal"); else printf("Not Equal"); return 0; }What is output?and why...
2 votes
2 votes
1 answer
4