Question
The integer value printed by the ANSI-C program given below is _______.
#include<stdio.h>
int funcp(){
static int x = 1;
x++;
return x;
}
int main(){
int x,y;
x = funcp();
y = funcp()+x;
printf("%d\n", (x+y));
return 0;
}Official answer and solution
- Official answer
- 7
- From
- Official GATE 2023 answer key
Solution
Trace the execution of funcp() with its persistent static variable across both invocations.
- In
funcp(),static int x = 1is initialized once when the program starts and retains its value between function calls. - First call
x = funcp()inmain():- Inside
funcp(), staticxis incremented from 1 to 2 (x++). funcp()returns 2.- Local variable
xinmain()becomes 2.
- Inside
- Second call
y = funcp() + xinmain():- Inside
funcp(), staticxis incremented from 2 to 3 (x++). funcp()returns 3.- Local
xinmain()is currently 2, soy = 3 + 2 = 5.
- Inside
- Output statement:
printf("%d\n", (x + y))prints .
Final answer
7
Common trap
Assuming static variable x reinitializes to 1 on the second call to funcp(), which would wrongly yield .
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2023 Computer Science and Information Technology (CS)
- Question
- 35 of 65
- 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.