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 ________.
View worked solution
Answer: 15
To find the value printed by the program, let us trace the execution step-by-step:
1. Variable Scope and Lifetime
- The global variable
stkTopis shadowed inside the functionstkFuncby the localstatic int stkTop. Therefore, the assignmentstkTop = -1inmain()has no effect on the stack operations. - The static variables
sizeandstkTopinsidestkFuncretain their values across multiple function calls.
2. Step-by-Step Execution
-
stkFunc(-1, 10);opcode = -1,val = 10.- Matches
case -1:size = 10. - Returns
-1.
-
stkFunc(0, 5);opcode = 0,val = 5.- Matches
case 0:sincestkTop (0) < size (10),A[0] = 5is assigned, andstkTopis incremented to1. - Returns
-1.
-
stkFunc(0, 10);opcode = 0,val = 10.- Matches
case 0:sincestkTop (1) < size (10),A[1] = 10is assigned, andstkTopis incremented to2. - Returns
-1.
-
stkFunc(1, 0) + stkFunc(1, 0)- For both calls,
opcode = 1, which triggers thedefaultcase. - The
defaultcase executes:if (stkTop) return A[--stkTop]; - First pop operation:
stkTopis decremented from2to1, returningA[1] = 10. - Second pop operation:
stkTopis decremented from1to0, returningA[0] = 5.
- For both calls,
The sum of the two returned values is:
Thus, the value printed by the program is 15.
Free practice · Your answers on this page are not saved.
