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 48.

Question

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;

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

Solution

Trace C code execution when static variables are replaced by automatic/register storage variables.

  1. Variable replacements:
  • In main(): auto int a = 1;
  • In prtFun(): register int a = 2; (automatic duration; reinitialized on every function entry).
  1. Execution trace:
  • Call 1 to prtFun():
    • Register a initialized to 2, auto b initialized to 1.
    • ++b becomes 2.
    • a += ++b becomes 2 + 2 = 4.
    • Prints 4 2.
  • In main():
    • a += 1 makes main's auto a = 2.
  • Call 2 to prtFun():
    • Because a is a register variable (not static), it is reinitialized to 2!
    • Auto b is initialized to 1.
    • ++b becomes 2.
    • a += ++b becomes 2 + 2 = 4.
    • Prints 4 2.
  • In main():
    • Prints main's a (2) and global b (0): 2 0.
  1. Output sequence:
    4 2
    4 2
    2 0

  2. This matches option (D).

Final answer

D

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
49 of 65, printed as CS Q.49
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.