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;
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.
- Variable replacements:
- In
main():auto int a = 1; - In
prtFun():register int a = 2;(automatic duration; reinitialized on every function entry).
- Execution trace:
- Call 1 to
prtFun():- Register
ainitialized to 2, autobinitialized to 1. ++bbecomes 2.a += ++bbecomes2 + 2 = 4.- Prints
4 2.
- Register
- In
main():a += 1makes main's autoa = 2.
- Call 2 to
prtFun():- Because
ais a register variable (not static), it is reinitialized to 2! - Auto
bis initialized to 1. ++bbecomes 2.a += ++bbecomes2 + 2 = 4.- Prints
4 2.
- Because
- In
main():- Prints main's
a(2) and globalb(0):2 0.
- Prints main's
-
Output sequence:
4 2
4 2
2 0 -
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.