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.

  1. In funcp(), static int x = 1 is initialized once when the program starts and retains its value between function calls.
  2. First call x = funcp() in main():
    • Inside funcp(), static x is incremented from 1 to 2 (x++).
    • funcp() returns 2.
    • Local variable x in main() becomes 2.
  3. Second call y = funcp() + x in main():
    • Inside funcp(), static x is incremented from 2 to 3 (x++).
    • funcp() returns 3.
    • Local x in main() is currently 2, so y = 3 + 2 = 5.
  4. Output statement:
    • printf("%d\n", (x + y)) prints x+y=2+5=7x + y = 2 + 5 = 7.
Final answer

7

Common trap

Assuming static variable x reinitializes to 1 on the second call to funcp(), which would wrongly yield 2+(2+2)=62 + (2 + 2) = 6.

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.