2 min read

[EVM - 1] Stacks, a primer

[EVM - 1]  Stacks, a primer
Photo by Sean Stratton / Unsplash

EVM is a stack-based computer. All instructions take their parameters from the stack, and write their results on the stack. Therefore, we start our journey from stacks.

This article will give a quick overview of the stack data structure. If you are already familiar with this data structure, feel free to skip to the next article.

A Stack is a linear data structure that holds elements much like arrays, except it follows a particular order in which operations are followed for the elements in the stack. With stacks, insertions and removals are done in a  particular ways:

  • "LIFO" -- that is "last in, first out”
  • “FILO” — that is "first in, last out”

We will focus on LIFO stacks, as that is what EVM uses.

The data structure is named stack as it behaves like a real-world stack, for example – a deck of cards or a pile of books. However,  I find it easier to think of a LIFO stack as a a can of tennis balls. If you put balls numbered 1, 2, and 3 in that order into a tennis ball can. they can only be removed in the order 3, 2, 1.

This real-world stack allows operations at one end only, that is from the top .

Once a stack is initialized, there are two primary operations

  • push() − Pushing an element on top of the stack. This is used for storing data
  • pop() − Removing an element from top of the stack. This is used for accessing data
Push and pop operation on stacks

At all times, we maintain a pointer to the last pushed data on the stack. As this pointer always represents the top of the stack, hence named top

This leads to a secondary operation:

  • peek() - get the top data element of the stack, without removing it.

There are a couple more secondary operations that helps us with efficient use of stacks by giving us information about state of the stack:

  • isFull() − check if stack is full.
  • isEmpty() − check if stack is empty.

Well, that is all you need to know about stacks before learning how we use them in EVM.

With this knowledge in our back pocket, let’s start with EVM.