Ground Embedded KO Subscribe

Notes / Data Structures & Algorithms

Queue and stack: first come and last come

A work queue is a queue; function calls are a stack. Implement both directly with arrays and see the difference.

GROUND EMBEDDED · NOTEData Structures & Algorithms 03Queues and stacksBUFFERhead →tail →write · read

Queue: first in, first out (FIFO)

Put (back)CBAGet (front)A comes first
Queue. Put in at the back, take out from the front.

Data where order matters (button events, packets waiting to be sent, a list of commands) is stacked in a queue. A ring buffer is exactly a fixed-size queue. An RTOS message queue is the same idea with locking and waiting added.

Stack: last in, first out (LIFO)

AbottomBCtopPopC comes first
Stack. Take out from where you put in.
static int16_t st[16];
static uint8_t top;
void push(int16_t v) { if (top < 16) st[top++] = v; }
int16_t pop(void)    { return top ? st[--top] : 0; }

The CPU, too, pushes the return address and local variables on a stack when it calls a function, because the function called last finishes first. A stack is also the natural fit for implementing "back" in a menu screen.

Which to use when

Situation Structure
Process in arrival order Queue
Going back, nested structures Stack
Most urgent first Priority queue

In embedded work both are built as fixed-size arrays, and what happens on overflow (drop, overwrite, flag an error) is decided from the start.

FREE PDFGet the 3 free ebooksIf you want to keep reading this topic as one book: BLDC motor control, serial communication and sensors at book length. PDFs are in Korean.Get them free →