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(): local int x = 1;
  • Expression: x += f1() + f2() + f3() + f2();

Trace function calls in sequence:

  1. f1():
    • Defines local int x = 25;
    • x++; gives 26.
    • Returns 26.
  2. f2() (first call):
    • Uses static int x = 50; (retains value across calls)
    • x++; increments static x to 51.
    • Returns 51.
  3. f3():
    • Operates on the global variable x (which is 10)
    • x *= 10; sets global x = 100.
    • Returns 100.
  4. f2() (second call):
    • Static x is currently 51.
    • x++; increments static x to 52.
    • Returns 52.

Sum of return values:

sum=26+51+100+52=229\text{sum} = 26 + 51 + 100 + 52 = 229

In main():
x += 229 sets local x = 1 + 229 = 230.
printf("%d", x); prints 230.

Final answer

230

Common trap

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.