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?
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 variableainsidemain()(let's call itmain_a), initialized to1.
First Call to prtFun():
- Inside
prtFun(),static int a = 2;declares a static local variable (let's call itprt_a), initialized to2. int b = 1;: A local auto variablebis initialized to1.a += ++b;:++bis a pre-increment operation, sobbecomes2.prt_a += 2updatesprt_ato .
printf(" \n %d %d ", a, b);prints the localprt_aand localb:4 2
Back in main():
a += 1;: This updates the local static variablemain_afrom1to2.
Second Call to prtFun():
- Since
prt_ais static, it retains its previous value of4. - The local auto variable
bis re-initialized to1. a += ++b;:++bincrementsbto2.prt_a += 2updatesprt_ato .
printf(" \n %d %d ", a, b);prints:6 2
Final Print in main():
printf(" \n %d %d ", a, b);:arefers to the local static variablemain_a, which has the value2.bis not declared locally inmain(), so it refers to the global variableb, which is0.
- 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.
