Consider the following C code segment. int a, b, c = 0; void prtFun(void);…
2012
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?
- A.
\(\begin{array}{llll} 3 & & 1 & \\ 4 & & 1 & \\ 4 & & 2 & \end{array}\) - B.
\(\begin{array}{lll} 4 & & 2 & \\ 6 & & 1 & \\ 6 & & 1 & \end{array}\) - C.
\(\begin{array}{lll} 4 & & 2 & \\ 6 & & 2 & \\ 2 & & 0 & \end{array}\) - D.
\(\begin{array}{lll} 3 & & 1 & \\ 5 & & 2 & \\ 5 & & 2 & \end{array}\)
Attempted by 129 students.
Show answer & explanation
Correct answer: C
Key points: static variables retain their values across calls and each function has its own separate static variable with the same name; local (automatic) variables are reinitialized each call; global variables default to 0 if not explicitly initialized.
Initial values: global a = 0, global b = 0. The static a inside main is initialized to 1. The static a inside the function is initialized to 2.
First call to the function:
Local b is set to 1, then ++b makes b = 2.
Function's static a becomes 2 + 2 = 4.
The function prints: "4 2".
Back in main: the static a in main is incremented by 1, so it becomes 1 + 1 = 2.
Second call to the function:
Local b is again set to 1, then ++b makes b = 2.
Function's static a becomes previous 4 + 2 = 6.
The function prints: "6 2".
Final print in main: main's static a is 2 and the global b is 0, so main prints: "2 0".
Final output (each on a new line):
4 2
6 2
2 0