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:

  1. A = B; stkTop = -1; initializes pointer A to array B[20].
  2. stkFunc(-1, 10): matches case -1. Sets size = 10. Returns -1.
  3. stkFunc(0, 5): matches case 0. Since stkTop (0) < size (10), writes A[0] = 5, then increments local stkTop to 1. Returns -1.
  4. stkFunc(0, 10): matches case 0. Since stkTop (1) < size (10), writes A[1] = 10, then increments local stkTop to 2. Returns -1.
  1. Now evaluate stkFunc(1, 0) + stkFunc(1, 0):
    Both calls have opcode = 1, matching default: if (stkTop) return A[--stkTop];.
  • One call decrements stkTop from 2 to 1 and returns A[1] = 10.
  • The other call decrements stkTop from 1 to 0 and returns A[0] = 5.

The sum is:

10+5=15.10 + 5 = 15.
Final answer

15

Common trap

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.