Open In App

C Quiz – 111 | Question 2

Like Article
Like
Save
Share
Report

Pick the best statement for the following program snippet:




#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;
}


(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


Last Updated : 28 Jun, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads