Common data questions

Common Data for Questions 48 and 49:

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);
}

Shared with question 49.

Question

What output will be generated by the given code segment?

Choose one option
Official answer and solution
Official answer
C
From
Official GATE 2012 answer key

Solution

Trace variable scopes and static variable retention across function calls in C.

  1. Initial declarations:
  • Global: int a = 0, b = 0, c = 0;
  • main() defines local static int a = 1;.
  • prtFun() defines local static int a = 2; and auto int b = 1;.
  1. Execution trace:
  • Call 1 to prtFun():
    • Inside prtFun: static local a = 2, local b = 1.
    • ++b increments local b to 2.
    • a += ++b sets a = 2 + 2 = 4.
    • Prints 4 2.
  • Back in main():
    • a += 1: main's static a becomes 1+1=21 + 1 = 2.
  • Call 2 to prtFun():
    • Inside prtFun: static a retains 4 from previous call. Auto b is reinitialized to 1.
    • ++b increments local b to 2.
    • a += ++b sets a = 4 + 2 = 6.
    • Prints 6 2.
  • Back in main():
    • printf("\n %d %d ", a, b);
    • Local static a in main is 2.
    • b is not declared locally in main, so it accesses global b, which is 0.
    • Prints 2 0.
  1. Output sequence:
    4 2
    6 2
    2 0

  2. This matches option (C).

Final answer

C

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2012 Computer Science and Information Technology (CS)
Question
48 of 65, printed as CS Q.48
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.