Structs & Data Structures · intermediate · ~10 min

Queues (FIFO)

Implement a FIFO queue with a circular buffer.

Lesson

A queue: first in, first out. Adding goes at the back (enqueue); removing comes from the front (dequeue).

The classic array implementation is a ring buffer: a fixed-capacity array with head and len indices, indexed modulo capacity. Reuses storage without shifting.

Code examples

typedef struct {
    int *buf; size_t cap, len, head;
} queue_t;
int q_enq(queue_t *q, int v) {
    if (q->len == q->cap) return -1;
    q->buf[(q->head + q->len) % q->cap] = v;
    q->len++; return 0;
}

Common mistakes

  • Forgetting to mod by cap on insert/remove — overflows past the array.
  • Confusing (head + len) % cap (tail) with just len.