Definition of Stack in Programming

Young man programming
vgajic/Getty Images

A stack is an array or list structure of function calls and parameters used in modern computer programming and CPU architecture. Similar to a stack of plates at a buffet restaurant or cafeteria, elements in a stack are added or removed from the top of the stack, in a “last in first, first out” or LIFO order.

The process of adding data to a stack is referred to as a “push,” while retrieving data from a stack is called a “pop.” This occurs at the top of the stack.

A stack pointer indicates the extent of the stack, adjusting as elements are pushed or popped to a stack.

When a function is called, the address of the next instruction is pushed onto the stack.

When the function exits, the address is popped off the stack and execution continues at that address.

Actions on the Stack

There are other actions that can be performed on a stack depending on the programming environment.

  • Peek: Allows the inspection of the topmost element on a stack without actually removing the element.
  • Swap: Also referred to as “exchange,” the positions of the two top elements of the stack are swapped, the first element becoming the second and the second becoming the top.
  • Duplicate: The topmost element is popped from the stack and then pushed back onto the stack twice, creating a duplicate of the original element.
  • Rotate: Also referred to as “roll,” specifies the number of elements in a stack which are rotated in their order. For example, rotating the top four elements of a stack would move the topmost element into the fourth position while the next three elements move up one position.

    The stack is also known as "Last In First Out (LIFO)".

    Examples: In C and C++, variables declared locally (or auto) are stored on the stack.