Consider the C program below. #include <stdio.h> int *A, stkTop; int stkFunc…

2015

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 __________.

Attempted by 59 students.

Show answer & explanation

Correct answer: 15

Answer: 15

Explanation: The function stkFunc uses local static variables (size and stkTop) that are separate from the global stkTop. The calls perform push and pop operations on the array pointed to by A.

  • stkFunc(-1, 10) sets the local static size to 10.

  • stkFunc(0, 5) pushes 5 into A[0], incrementing the local stkTop from 0 to 1.

  • stkFunc(0, 10) pushes 10 into A[1], incrementing the local stkTop to 2.

  • Each stkFunc(1, 0) call decrements the local stkTop and returns the popped value. The two pops return 10 and then 5, so their sum is 15.

  • The assignment stkTop = -1 in main modifies the global variable, but the function uses its own static stkTop, so the global change has no effect on the pushes/pops.

Therefore the program prints 15.

Explore the full course: Gate Guidance By Sanchit Sir