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.](../../assets/questions/CS-2015-S2-Q52-1.webp)
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.