Definition of a Stack
In computer programming, a stack is a concept in which we have set aside a location to hold a
stack of items, but we can only get to the one on top. The rest of the items are mostly
unreachable beneath the top one. We can only get to the top item because a stack is really an
abstract structure where the last item you put into it must be removed first in order to reach
previous items. We call this last in first out, or LIFO. Computer stacks are really handy because
they allow us to reserve temporary storage, so we can pass numbers (or program pointers and
program variables, which are a lot like numbers) between program functions (a function does
stuff with numbers).
A really good way to visualize a stack is to picture a stack of plates in a cafeteria. You couldn't
grab one from the middle very easily, could you? No, when you're standing in line in a cafeteria,
you don't want to slow down people behind you, so you grab what's on top. Computer stacks
work in pretty much the same way, so programs can run really fast. In essence, items on a stack
are removed in reverse order (the last to go in are the first to come out).
Stack Push & Pop
When you add an item (often called an element) to the top of a stack, that's called a push. Push
is a good word for this, because the new item pushes all the old ones down. If you've ever
worked in a cafeteria or restaurant kitchen, spring-loaded shafts for plates are super common.
The weight of the plates on top push the lower plates down.
When you remove an item from a stack, that's called a pop. In a cafeteria, when you remove
the topmost plate, the ones beneath it pop up because of the spring beneath them. Well, a
computer stack is kind of like that.
Stack Underflow & Overflow
Now that we have a basic picture in mind of what a stack conceptually looks like, we can define
what underflow and overflow are. Stack underflow happens when we try to pop (remove) an
item from the stack, when nothing is actually there to remove. This will raise an alarm of sorts
in the computer because we told it to do something that cannot be done.
Stack overflow happens when we try to push one more item onto our stack than it can actually
hold. You see, the stack usually can hold only so much stuff. Typically, we allocate (set aside)
where the stack is going to be in memory and how big it can get. So, when we stick too much
stuff there or try to remove nothing, we will generate a stack overflow condition or stack
underflow condition, respectively.