Behold the Stack, Part V

Pulling in all the stack items mentioned in last week’s Lesson, I present to you a C program that emulates stack storage. I’m certain this presentation will be one of the highlights of your programming career.

I’m joshing, of course. Many programming concepts are good to know, even if you never use them. And my advice is never to force anything just to meet some artificial standard. For example, I’ve seen a lot of object oriented code that could have been written in a procedural manner, but I digress.

The following code contains stack emulation elements. It prompts the user for integer input, up to 16 values. Each value is pushed onto stack storage. After typing the values, each is popped from the stack:

#include <stdio.h>

void push(int v);
int pop(void);

#define STACK_SIZE 16

int stack[STACK_SIZE];
int *sp;

int main()
{
    int s,a;

    sp = stack;     /* initialize the stack pointer */
    s = 0;

    while(s < STACK_SIZE)
    {
        printf("Enter a value to push on the stack, 0 to end: ");
        scanf("%d",&a);
        if(a == 0) break;
        push(a);
        s++;
    }

    while(s)
    {
        printf("Popping %d from the stack\n",pop());
        s--;
    }

    return(0);
}

void push(int v)
{
    if(sp == stack+STACK_SIZE)
    {
        puts("Stack Overflow");
    }
    else
    {
        sp++;
        *sp = v;
    }
}

int pop(void)
{
    if( sp == stack)
    {
        puts("Stack Empty");
        return(0);
    }
    else
    {
        return(*sp--);
    }
}

A while loop at Line 18 processes input. Variable s tracks integers in variable a that are pushed onto the stack

Line 22 checks for early termination when 0 is input. Otherwise, the push() statement at Line 23 sends the value to the stack.

A second while loop at Line 27 pops values from the stack.

Here is sample output:

Enter a value to push on the stack, 0 to end: 100
Enter a value to push on the stack, 0 to end: 200
Enter a value to push on the stack, 0 to end: 300
Enter a value to push on the stack, 0 to end: 0
Popping 300 from the stack
Popping 200 from the stack
Popping 100 from the stack

In my programming career, I’ve never needed to emulate a stack in any of my C code. I might have done so and not recognized it as such. Then again, in Assembly, using the stack is vital and something you take care to monitor. In fact, recursion freaks me out in C because I’m aware of how much this technique uses the stack and the potential for a stack overflow. That’s always possible, of course, even when you emulate stack storage.

Leave a Reply