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 ;
Line 2 is replaced by register int ;
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 to0by default. Thus, global and global . - Inside
main():
Line 1 is replaced byauto int a = 1;. This creates a local variable insidemain(), initialized to . - Inside
prtFun():
Line 2 is replaced byregister int a = 2;. Aregistervariable has local scope and automatic lifetime (similar toauto). It is re-allocated and re-initialized to every timeprtFun()is called.int b = 1;is a local automatic variable, re-initialized to on every call.
2. Step-by-Step Trace
Step 1: First call to prtFun() from main()
- Local variable (register) is initialized to .
- Local variable (auto) is initialized to .
- The statement
a += ++b;is executed:++bpre-increments local from to .a += 2updates local to .
printf(" \n %d %d ", a, b);prints the local variables ofprtFun():
Output:4 2
Step 2: Return to main() and increment
a += 1;modifies the local variable ofmain().
Local becomes .
Step 3: Second call to prtFun() from main()
- Since is a
registervariable (notstatic), it does not retain its previous value. It is re-initialized to . - Local is re-initialized to .
- The statement
a += ++b;is executed:++bincrements local from to .a += 2updates local to .
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 insidemain():- The variable
arefers to the local variable ofmain(), which has the value . - The variable
brefers to the global variable (since there is no local variable declared inmain()), which has the value .
- The variable
- Output:
2 0
Conclusion
The complete output generated is:4 2 4 2 2 0This matches Option D.
Free practice · Your answers on this page are not saved.
