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 if:

Line 1 is replaced by auto int a = 1;

Line 2 is replaced by register int a = 2;

  1. A.

    \(\begin{array}{ll} \text{3} & \text{1} \\ \text{4} & \text{1} \\ \text{4} & \text{2} \\ \end{array}\)

  2. B.

    \(\begin{array}{ll} \text{4} & \text{2} \\ \text{6} & \text{1} \\ \text{6} & \text{1} \\ \end{array}\)

  3. C.

    \(\begin{array}{ll} \text{4} & \text{2} \\ \text{6} & \text{2} \\ \text{2} & \text{0} \\ \end{array}\)

  4. D.

    \(\begin{array}{ll} \text{4} & \text{2} \\ \text{4} & \text{2} \\ \text{2} & \text{0} \\ \end{array}\)

Attempted by 165 students.

Show answer & explanation

Correct answer: D

Key insight: understand storage duration and scope. The replacement creates an automatic local a in main (auto) and an automatic register-local a in prtFun (register). The register-local a is reinitialized on every call; globals are zero-initialized.

  1. Initial state: global variables at file scope are zero-initialized, so the global b is 0. In main an automatic local a is initialized to 1 and hides the global a.

  2. First call to prtFun: register a is initialized to 2; local b is set to 1. ++b makes b = 2, then a += ++b makes a = 2 + 2 = 4. prtFun prints: 4 2.

  3. Back in main: the automatic local a (which was 1) is incremented by 1, so main's a becomes 2.

  4. Second call to prtFun: register a is reinitialized to 2 again (it does not retain the previous value). Local b again becomes 2 and a becomes 4, so prtFun prints: 4 2.

  5. Final printf in main prints main's automatic a (2) and the global b (0): 2 0.

Final output (in order):

  • 4 2

  • 4 2

  • 2 0

Explore the full course: Gate Guidance By Sanchit Sir