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?
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.
- Initial declarations:
- Global:
int a = 0, b = 0, c = 0; main()defines localstatic int a = 1;.prtFun()defines localstatic int a = 2;and autoint b = 1;.
- Execution trace:
- Call 1 to
prtFun():- Inside
prtFun: static locala = 2, localb = 1. ++bincrements localbto 2.a += ++bsetsa = 2 + 2 = 4.- Prints
4 2.
- Inside
- Back in
main():a += 1: main's staticabecomes .
- Call 2 to
prtFun():- Inside
prtFun: staticaretains 4 from previous call. Autobis reinitialized to 1. ++bincrements localbto 2.a += ++bsetsa = 4 + 2 = 6.- Prints
6 2.
- Inside
- Back in
main():printf("\n %d %d ", a, b);- Local static
ainmainis 2. bis not declared locally inmain, so it accesses globalb, which is 0.- Prints
2 0.
-
Output sequence:
4 2
6 2
2 0 -
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.