Skip to content
Related Articles

Related Articles

C | Storage Classes and Type Qualifiers | Question 19
  • Difficulty Level : Medium
  • Last Updated : 26 Feb, 2013

Output? (GATE CS 2012)




#include <stdio.h>
int a, b, c = 0;
void prtFun (void);
int main ()
{
    static int a = 1; /* line 1 */
    prtFun();
    a += 1;
    prtFun();
    printf ( "\n %d %d " , a, b) ;
}
   
void prtFun (void)
{
    static int a = 2; /* line 2 */
    int b = 1;
    a += ++b;
    printf (" \n %d %d " , a, b);
}

(A) 3 1
4 1
4 2
(B) 4 2
6 1
6 1
(C) 4 2
6 2
2 0
(D) 3 1
5 2
5 2


Answer: (C)

Explanation: ‘a’ and ‘b’ are global variable. prtFun() also has ‘a’ and ‘b’ as local variables. The local variables hide the globals (See Scope rules in C). When prtFun() is called first time, the local ‘b’ becomes 2 and local ‘a’ becomes 4.
When prtFun() is called second time, same instance of local static ‘a’ is used and a new instance of ‘b’ is created because ‘a’ is static and ‘b’ is non-static. So ‘b’ becomes 2 again and ‘a’ becomes 6.
main() also has its own local static variable named ‘a’ that hides the global ‘a’ in main. The printf() statement in main() accesses the local ‘a’ and prints its value. The same printf() statement accesses the global ‘b’ as there is no local variable named ‘b’ in main. Also, the defaut value of static and global int variables is 0. That is why the printf statement in main() prints 0 as value of b.

Quiz of this Question

Want to learn from the best curated videos and practice problems, check out the C Foundation Course for Basic to Advanced C.
My Personal Notes arrow_drop_up
Recommended Articles
Page :