Question
Consider the following C program.
#include <stdio.h>
int f1(void);
int f2(void);
int f3(void);
int x = 10;
int main()
{
int x = 1;
x += f1() + f2() + f3() + f2();
printf("%d", x);
return 0;
}
int f1() { int x = 25; x++; return x; }
int f2() { static int x = 50; x++; return x; }
int f3() { x *= 10; return x; }
The output of the program is _____.
Official answer and solution
- Official answer
- 230
- From
- Official GATE 2015 answer key
Solution
Trace variable scopes, lifetime of static variables, and modifications to global state.
The program has:
- Global variable
int x = 10; - In
main(): localint x = 1; - Expression:
x += f1() + f2() + f3() + f2();
Trace function calls in sequence:
f1():- Defines local
int x = 25; x++;gives 26.- Returns 26.
- Defines local
f2()(first call):- Uses
static int x = 50;(retains value across calls) x++;increments staticxto 51.- Returns 51.
- Uses
f3():- Operates on the global variable
x(which is 10) x *= 10;sets globalx = 100.- Returns 100.
- Operates on the global variable
f2()(second call):- Static
xis currently 51. x++;increments staticxto 52.- Returns 52.
- Static
Sum of return values:
In main():
x += 229 sets local x = 1 + 229 = 230.
printf("%d", x); prints 230.
230
Reinitializing the static variable x in f2() to 50 on the second call instead of retaining its value 51.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2015 Computer Science and Information Technology (CS) Session 3
- Question
- 64 of 65, printed as CS Q.54
- 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.