C Quiz – 111 | Question 2

Pick the best statement for the following program snippet:

filter_none

edit
close

play_arrow

link
brightness_4
code

#include "stdio.h"
void foo(void)
{
 static int staticVar;
 staticVar++;
 printf("foo: %d\n",staticVar);
}
  
void bar(void)
{
 static int staticVar;
 staticVar++;
 printf("bar: %d\n",staticVar);
}
  
int main()
{
 foo(), bar(), foo();
 return 0;
}

chevron_right


(A) Compile error because same static variable name is used in both foo and bar. Since these static variables retain their values even after function is over, same name can’t be used in both the functions.

(B) Compile error because semicolon isn’t used while calling foo() and bar() in side main function.
(C) No compile error and only one copy of staticVar would be used across both the functions and that’s why final value of that single staticVar would be 3.
(D) No compile error and separate copies of staticVar would be used in both the functions. That’s why staticVar in foo() would be 2 while staticVar in bar() would be 1.


Answer: (D)

Explanation: Here, even though life of static variables span across function calls but their scope is respective to their function body only. That’s why staticVar of each function has separate copies whose life span across function calls. And d is correct.

Quiz of this Question



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.