Question
Consider the C program below.
#include <stdio.h>
int *A, stkTop;
int stkFunc(int opcode, int val)
{
static int size=0, stkTop=0;
switch (opcode) {
case -1: size = val; break;
case 0: if (stkTop < size) A[stkTop++] = val; break;
default: if (stkTop) return A[--stkTop];
}
return -1;
}
int main()
{
int B[20]; A = B; stkTop = -1;
stkFunc (-1, 10);
stkFunc ( 0, 5);
stkFunc ( 0, 10);
printf ("%d\n", stkFunc(1, 0) + stkFunc(1, 0));
}
The value printed by the above program is _____.
Official answer and solution
- Official answer
- 15
- From
- Official GATE 2015 answer key
Solution
Trace the execution of stkFunc, noting that the local static variable stkTop shadows the global stkTop.
Inside stkFunc, the declaration:
static int size=0, stkTop=0;
defines static local variables with lifetime across all calls, completely shadowing the global int stkTop.
Trace of calls in main:
A = B; stkTop = -1;initializes pointerAto arrayB[20].stkFunc(-1, 10): matchescase -1. Setssize = 10. Returns-1.stkFunc(0, 5): matchescase 0. SincestkTop (0) < size (10), writesA[0] = 5, then increments localstkTopto 1. Returns-1.stkFunc(0, 10): matchescase 0. SincestkTop (1) < size (10), writesA[1] = 10, then increments localstkTopto 2. Returns-1.
- Now evaluate
stkFunc(1, 0) + stkFunc(1, 0):
Both calls haveopcode = 1, matchingdefault: if (stkTop) return A[--stkTop];.
- One call decrements
stkTopfrom 2 to 1 and returnsA[1] = 10. - The other call decrements
stkTopfrom 1 to 0 and returnsA[0] = 5.
The sum is:
15
Thinking that stkTop = -1 in main corrupts array indexing, failing to realize the local static stkTop = 0 shadows it.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2015 Computer Science and Information Technology (CS) Session 2
- Question
- 48 of 65, printed as CS Q.38
- 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.