The GATE Grind

GATE 2012 CS (CS1) – Question 59

Programming and Data Structures · Programming in C · 2 marks · Multiple choice

For the same complete code below, replace Line 1 with auto int a=1 and Line 2 with register int a=2. What are the three output lines?

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);
}
  1. (3,1); (4,1); (4,2)
  2. (4,2); (6,1); (6,1)
  3. (4,2); (6,2); (2,0)
  4. (4,2); (4,2); (2,0)

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: (D) (4,2); (4,2); (2,0)

Explanation

The function’s register a now has automatic duration and is initialized to two on each call. Local b likewise begins at one, so each call prints (4,2). main’s automatic a survives through its one invocation and becomes two; global b remains zero. Final output is (2,0), yielding D.

More Programming in C questions

All Programming in C questions →