276 views
0 votes
0 votes

1 Answer

Best answer
3 votes
3 votes

If we run the same from main() , both of them will give 15..However if we call the above functions separately from main() , they will give different results..

The reason being we know :

Static variable is initialised exactly once for each function..By default it is initialised to 0 as in the second case.

 Now in the first code , x is initialised to 10 which on increment becomes 15..So the value of x which is in static storage area becomes 15 now.. So when next time this function is called , the value is not reinitialised to 10..It resumes from 15 only..Thus x+=5 in the second invocation leads to 20..Similarly in next turn , it will give 25 and so on..

However in the second case , x is initialised to 0 which is by default..Then x is assigned 10 and then incremented to 15..So for next time invocation the value remains 15 and not re initialised to 0..But then the step : x = 10 will make the value of x equal to 10 once again and hence x += 5 will lead to the value of 15..This way it will continue and every time the second function will give the value of 15..

Hence they give same output for the first time only..From second time they differ..Hence according to the given options , B) should be the most appropriate option..

selected by

Related questions

0 votes
0 votes
1 answer
1
2 votes
2 votes
2 answers
4
atulcse asked Jan 15, 2022
686 views
Consider the following programint find (int n) { int a = 1; for (i = 1; i < = n; i ++) for (j = 1; j < = i; j++) for (k = 1; k <= j, k++) a = a + 1; ...