Skip to content
Official PYQ · 2012

GATE CS 2012 Q48 — 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?
 

Choose one option
View worked solution

Answer: C

To find the output of the given C program, let's trace the execution step-by-step, keeping track of the scope and lifetime of the variables.

1. Global Variables

The global variables are declared as:

int a, b, c = 0;

Since they are global, they are initialized to 0 by default:

  • Global a = 0
  • Global b = 0
  • Global c = 0

2. Execution of main()

  • static int a = 1;: This declares a static local variable a inside main() (let's call it main_a), initialized to 1.

First Call to prtFun():

  • Inside prtFun(), static int a = 2; declares a static local variable (let's call it prt_a), initialized to 2.
  • int b = 1;: A local auto variable b is initialized to 1.
  • a += ++b;:
    • ++b is a pre-increment operation, so b becomes 2.
    • prt_a += 2 updates prt_a to 2+2=42 + 2 = 4.
  • printf(" \n %d %d ", a, b); prints the local prt_a and local b:
    4 2

Back in main():

  • a += 1;: This updates the local static variable main_a from 1 to 2.

Second Call to prtFun():

  • Since prt_a is static, it retains its previous value of 4.
  • The local auto variable b is re-initialized to 1.
  • a += ++b;:
    • ++b increments b to 2.
    • prt_a += 2 updates prt_a to 4+2=64 + 2 = 6.
  • printf(" \n %d %d ", a, b); prints:
    6 2

Final Print in main():

  • printf(" \n %d %d ", a, b);:
    • a refers to the local static variable main_a, which has the value 2.
    • b is not declared locally in main(), so it refers to the global variable b, which is 0.
  • This prints:
    2 0

Conclusion

The generated output is:

4  2
6  2
2  0

This corresponds to Option C.

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

Published
Report a correction
Keep exploringMore Programming in C questions