GATE / CS ARCHIVE

GATE CSE 2015 SET 2 / QUESTION 52

GATE CSE 2015 Set 2 Q52

Programming in C · Scope, Lifetime & Storage Classes · Full GATE CSE 2015 Set 2 paper

GATE 2015 Set 2, Q52 2 marks · NAT
Report issue

Scope, Lifetime & Storage Classes

Question 52, GATE 2015: A global int pointer A and global stkTop coexist with stkFunc’s static int size=0, stkTop=0. Opcode −1 sets size=val; opcode 0 pushes A[stkTop++]=val when stkTop<size; the default returns A[--stkTop] if nonempty, otherwise −1. main points A at B[20], sets global stkTop=−1, sets capacity 10, pushes 5 then 10, and prints stkFunc(1, 0)+stkFunc(1, 0). Find the output.
Tap to enlarge
Answer & solution

Official answer: 15

The function-local static stkTop starts at 0 and shadows the global stkTop, so assigning the global variable−1 does not affect the stack. After configuring size 10 and pushing 5 then 10, the two pops return 10 and 5 in whichever operand-evaluation order is chosen. Their sum is 15. Although the + operands have unspecified order, the two function executions are indeterminately sequenced rather than interleaving their bodies; this is not the direct unsequenced-increment case.

Track the function-local static top, not the global of the same name. Capacity initialization leaves the local top at 0. Pushing 5 writes B[0] and changes it to 1; pushing 10 writes B[1] and changes it to 2. The two calls then return 10 and 5, in whichever operand-call order is chosen. Their sum is 15. A function’s static local persists between calls, and lexical scope makes it hide the global stkTop, so setting that global to −1 does not underflow this stack.

Original paper, page 46 · Answer key