IAE Academy

GATE 2023 CS Q.35: solution and answer

GATE 2023 · CSQ.35 · 1 mark · NAT

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;
}
See the question in the paper

Answer and solution

ANSWER

The program prints 7.

Official answer: 7Source: Official answer key, GATE 2023 CS (IIT Kanpur)

  1. funcp declares static int x = 1. A static local variable is initialized exactly once (at first call) and its value is retained across calls to funcp. main separately declares its own automatic int x, y, unrelated to funcp's static x — they merely share a name.

  2. First call: x = funcp(); — inside funcp, x++ takes the static x from 1 to 2, and funcp returns 2. This is assigned to main's x, so main's x = 2.

  3. Second call: y = funcp() + x; — inside funcp, x++ takes the static x from 2 to 3, and funcp returns 3. In this same statement, main's x is only read, never modified, so there is no sequencing hazard: regardless of evaluation order, main's x reads as its already-assigned value, 2.

  4. So y = 3 + 2 = 5.

  5. printf("%d\n", (x+y)) prints main's x + y = 2 + 5 = 7.

KEY IDEA

A static local variable inside a function keeps its value across calls (initialized only once, at first entry) and is completely distinct from any same-named variable in the calling function; only reads (never a write) of a variable elsewhere in the same full expression are safe to reason about without worrying about C's unsequenced evaluation order.

WATCH OUT FOR

Confusing funcp's static x with main's local x and re-computing main's x using the static variable's latest value (e.g. wrongly taking main's x as 3 during the second call instead of the 2 it was already assigned), or assuming C's unspecified evaluation order makes y = funcp() + x undefined — it is not, because x is only read here, not modified, in this expression.

From the GATE 2023 CS paper. Every question of this paper · Download the full paper · All 7 Functions & scope questions, with notes

More Functions & scope questions