GATE / CS ARCHIVE

GATE CSE 2023 / QUESTION 35

GATE CSE 2023 Q35

Programming in C · Scope, Lifetime & Storage Classes · Full GATE CSE 2023 paper

GATE 2023, Q35 1 mark · NAT
Report issue

Scope, Lifetime & Storage Classes

Question 35, GATE 2023: In C, funcp has static int x=1, then increments x and returns it. main declares separate int x,y, executes x=funcp(); y=funcp()+x; and prints x+y. What integer is printed?
Tap to enlarge
Answer & solution

Official answer: 7

The static local x in funcp persists across calls. Its first call increments 1 to 2 and returns 2, assigned to main’s x. The second increments the same static value 2 to 3; main’s y becomes 3+2=5. Therefore main prints x+y=2+5=7. The local static and main’s x are distinct objects.

Teaching detail. A static local has block scope but static storage duration: its initialization occurs once, and the stored value survives a return from the function. It is not reinitialized to 1 at each invocation. Track the function's private x separately from main's x to avoid accidental overwriting: after the first call they both happen to equal 2, but the second call changes only the static variable to 3. main's previously stored x remains 2 and participates in both subsequent arithmetic expressions.

Original paper, page 33 · Answer key