GATE / CS ARCHIVE

GATE CSE 2012 / QUESTION 49

Automatic and register local lifetimes

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

GATE 2012, Q49 2 marks · MCQ
Report issue

Scope, Lifetime & Storage Classes

Question 49, 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);
}
Replace Line 1 by auto int a=1; and Line 2 by register int a=2;. What three 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) (4,2);(4,2);(2,0).
Question 49, 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);
}
Replace Line 1 by auto int a=1; and Line 2 by register int a=2;. What three 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) (4,2);(4,2);(2,0).
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Under the same intended valid-declarations assumptions as the preceding common-data question, changing main-local a to auto does not change its lifetime within this single invocation of main: it still becomes 2. Changing prtFun-local a to register gives it automatic storage duration, not persistent storage; each call initializes it to 2. Each call also initializes local b=1, increments b to 2, adds 2 to a, and prints (4, 2). Finally main prints its a=2 and the zero-initialized global b=0. The three output pairs are (4, 2), (4, 2), (2, 0), option D. register does not guarantee physical register allocation.

Check: Storage-class changes affect persistence, not lexical scope. Both modified declarations still shadow the same globals. The register local is recreated on every invocation, so it cannot retain the first call’s value 4 when the second call starts.

Original paper, page 13 · Answer key