The GATE Grind

GATE 2015 CS (CS2) – Question 52

Programming and Data Structures · Programming in C · 2 marks · Numerical answer

What does this C program print?

#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(void) {
  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));
}

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: 15

Explanation

The function’s static local stkTop shadows the global, so assigning global stkTop=−1 does not change the stack position. Initialization sets capacity ten. The pushes store five then ten. The two pop calls return ten and five in either evaluation order, summing to fifteen. Thus the printed number is fifteen.

More Programming in C questions

All Programming in C questions →