GATE / CS ARCHIVE

GATE CSE 2012 / QUESTION 48

Static local storage and variable shadowing

Programming in C · Scope, Lifetime & Storage Classes · Full GATE CSE 2012 paper

GATE 2012, Q48 2 marks · MCQ
Report issue

Scope, Lifetime & Storage Classes

Question 48, GATE 2012: Common code (source-era C syntax retained):
int a,b,c=0;
void prtFun(void);
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);
}
What three output pairs are printed?
(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).
Question 48, GATE 2012: Common code (source-era C syntax retained):
int a,b,c=0;
void prtFun(void);
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);
}
What three output pairs are printed?
(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).
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Assume the snippet is meant as a storage-duration exercise with an appropriate printf declaration and a valid int main(void) supplied; the printed implicit-int main and omitted stdio declaration are not a portable modern-C complete program. The file-scope b has static storage and starts at 0. In prtFun, local b starts at 1 on each call and ++b makes it 2. Its static a starts at 2 once, then becomes 4 on the first call and 6 on the second, printing (4, 2) and (6, 2). The separate main-local a starts at 1 and is incremented to 2; main sees global b=0 and prints (2, 0). Hence C.

Check: There are three different a objects and two different b objects. The function-local a persists across calls but is not main’s a; function-local b shadows global b and never changes it. Keeping an object-by-object trace avoids incorrectly carrying local b back into main.

Original paper, page 13 · Answer key