Skip to content
Official PYQ · 2012

GATE CS 2012 Q49 — Programming in C

Explain with AI

Consider the following C code segment.

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 output will be generated by the given code segment if:

Line 1 is replaced by auto int a=1a = 1;

Line 2 is replaced by register int a=2a = 2; 

Choose one option
View worked solution

Answer: D

To find the output of the given C code segment, let us trace the execution step-by-step with the specified modifications.

1. Variable Declarations and Scopes

  • Global variables:
    int a, b, c = 0;
    Since they are declared globally, they are initialized to 0 by default. Thus, global a=0a = 0 and global b=0b = 0.
  • Inside main():
    Line 1 is replaced by auto int a = 1;. This creates a local variable aa inside main(), initialized to 11.
  • Inside prtFun():
    Line 2 is replaced by register int a = 2;. A register variable has local scope and automatic lifetime (similar to auto). It is re-allocated and re-initialized to 22 every time prtFun() is called.
    int b = 1; is a local automatic variable, re-initialized to 11 on every call.
---

2. Step-by-Step Trace

Step 1: First call to prtFun() from main()

  • Local variable aa (register) is initialized to 22.
  • Local variable bb (auto) is initialized to 11.
  • The statement a += ++b; is executed:
    • ++b pre-increments local bb from 11 to 22.
    • a += 2 updates local aa to 2+2=42 + 2 = 4.
  • printf(" \n %d %d ", a, b); prints the local variables of prtFun():
    Output: 4 2

Step 2: Return to main() and increment

  • a += 1; modifies the local variable aa of main().
    Local aa becomes 1+1=21 + 1 = 2.

Step 3: Second call to prtFun() from main()

  • Since aa is a register variable (not static), it does not retain its previous value. It is re-initialized to 22.
  • Local bb is re-initialized to 11.
  • The statement a += ++b; is executed:
    • ++b increments local bb from 11 to 22.
    • a += 2 updates local aa to 2+2=42 + 2 = 4.
  • printf(" \n %d %d ", a, b); prints:
    Output: 4 2

Step 4: Return to main() and final print

  • printf(" \n %d %d ", a, b); is executed inside main():
    • The variable a refers to the local variable aa of main(), which has the value 22.
    • The variable b refers to the global variable bb (since there is no local variable bb declared in main()), which has the value 00.
  • Output: 2 0
---

Conclusion

The complete output generated is:
4  2
4  2
2  0
This matches Option D.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions