Course contentsShow
← C
Lesson 1010 of 1,21914. Data Structures in CFree lesson

The Pop operation

The Pop operation

What you'll learn: How to remove the top element from a Stack and retrieve its value using the LIFO principle.

In our last lesson, we learned how to "Push" data onto a Stack. But a container is only useful if we can get things back out! In the world of Stacks, the operation for removing data is called Pop.

The "Last In, First Out" rule

Think of a physical stack of heavy cafeteria trays. When you want a tray, you don't try to tug one out from the middle or the bottom—that would cause a messy collapse. Instead, you grab the one right on top.

This is the essence of LIFO (Last In, First Out). The very last item you placed on the stack is the very first one that must be removed. When you "Pop" an element, you are doing two things:

  1. Identifying the value currently at the top.
  2. Moving the "Top" marker down so the next item becomes the new leader.

How it works in C

To perform a Pop, we first check if the stack is empty (to avoid a "Stack Underflow" error). If there is data, we grab the value from the current top index and then decrement our counter.

Here is a conceptual look at how you might write a Pop function using an array-based stack:

#include <stdio.h>

int stack[5] = {10, 20, 30}; // A stack with 3 items
int top = 2;                // Index of the top item (30)

int pop() {
    if (top == -1) {
        printf("Stack is empty!\n");
        return -1;
    }

    // 1. Grab the value at the top
    int value = stack[top];

    // 2. Decrement top to "remove" the item
    top--;

    // 3. Return the value we just removed
    return value;
}

int main() {
    int removed = pop();
    printf("Popped value: %d\n", removed); // Outputs 30
    printf("New top index: %d\n", top);    // Index is now 1 (value 20)
    return 0;
}

Why decrementing is enough

Notice that in the code above, we didn't actually "erase" the number 30 from the array. We simply moved the top index down. In C, if our pointer or index no longer acknowledges a piece of memory as part of the stack, it is effectively gone. The next time we "Push" a new value, the old 30 will simply be overwritten.

Key takeaway

Popping retrieves the most recently added item and moves the stack pointer down by one.