in Programming in C edited by
1,031 views
1 vote
1 vote
void ab()
{
    auto int a;
    static int s= 5;
    a = ++s;
    printf("%d%d",a,s);
    if(a<= 7)
    ab();
    printf("%d%d",a,s);
}
void main()
{
    ab();
}



According to me answer should be- 667788887766 but the answer is - 667788887868. Please explain

in Programming in C edited by
1.0k views

2 Comments

static variable store in static part of memory and once changed then retain their value throughout the program.

So S will print 8 only after ending of each activation record.
0
0

667788887868 is correct answer. 

since, s is static & static variables are stored data area of memory, which is not destroyed. So, finally updated value of 's' (which is 8) will be printed, while coming back recursively.

However, a is auto so, it is stored in stack. so, each time local stack values will be taken for 'a' & stack is destroyed, while coming back recursively.

0
0

1 Answer

2 votes
2 votes
Best answer

Ans-667788887868

a is local variable and s is static variable so scope of local variable is local and it will destroy after function is over and scope of static variable is throughout the program.

selected by

6 Comments

can u explain again not getting
0
0
In the main ab() is called ,when ab() is called ,as in ab()  a is local variable(lifetime and scope is local) and s is static variable and here s is assigned  value 5 ,then a=++s so a will have value 6 and s will have value equal to 6 so 66 will be printed then condition will be check a<=7 (6<=7 true) so ab() will be called again without reaching the last line ,now a will be created again and s will not be created as it is static and a=++s will executed and now a and s will have 7 and 7 so 77 will be printed now again condition will be checked a<=7(7<=7 true) ,now ab() will be called one more time ,once again a will be created and a=++s will be executed so a and s will have value 8 and 8 so 88 will be printed ,then condition will be checked a<=7(8<=7 false) so execution will go to the last line ,now 887868 will be printed as i described in image so finally 667788887868 will be printed.
0
0
Thanks :)
0
0
thanks @Anil Ji
0
0
Anil ji you are so great
0
0
I did not get it. in last how 887868 is printed? when $8\leq7$ this condition is false then what happens?
0
0

Related questions