Queue Implementation in C, C++, Java, Python and C#: Arrays, Linked Lists and Deques

Three queue layouts in five languages: what each costs in memory and time, and why a circular queue needs a count, a spare slot or a flag.

A circular conveyor with eight slots, some filled, a blue parcel entering and a green parcel leaving, and a short chute of tied parcels.

A queue of one million ints takes 4,199,056 bytes of heap behind a circular array and 32,000,000 bytes behind a linked list, and the two differ only in where the next item waits. The circular version is the harder of the two to get right. With a head index and a tail index and nothing else, an empty ring and a full ring at capacity look identical: both have the same two indices. One extra field, either a count or a spare slot, removes the ambiguity, and the experiment later in this article measures what each of the three designs costs.

This guide implements first-in, first-out queues in C, C++, Java, Python and C# in three layouts: a growable circular array, a fixed-capacity ring and a singly linked list. It measures the heap each layout uses, the cost of std::queue over std::deque and over std::list, and three ways to tell a full ring from an empty one. Every program was compiled and run for this article on Ubuntu 24.04 under WSL2 (GCC 13.3 and Clang 18.1.3, warnings as errors) and on Windows 11 (MSVC 19.44, Java 27, Python 3.14.6 and .NET 10). Every output block below is captured from a real run, and the code is in five GitHub repositories whose workflows build and test it. The definition assumes no queue knowledge, and the measurements assume you have read the implementations.

What Is a Queue?

A queue is a linear data structure that removes items in the order they arrive: first in, first out (FIFO). New items join at the back, called the tail or rear, and only the item at the front can be removed. A queue exposes enqueue, dequeue, front, empty and size, and a well-built queue runs all of them in constant time, amortised for a growing array.

Two ends, two operations. push (also called enqueue or offer) adds an item at the tail. pop (dequeue or poll) removes the item at the front and returns it. front (peek) reads the oldest item without removing it. The names vary by library, as the language sections show, but the behaviour does not. A queue is the mirror image of the stack, which removes the most recent item, and that single difference decides where each structure is the right tool.

The abstract data type says nothing about storage. Both representations in this article keep the same two things: the position of the oldest item and the number of stored items. The circular array stores the elements themselves in one allocation and wraps the tail back to slot 0 when it reaches the end. The linked list stores each element in its own node with a pointer to the next node, and keeps pointers to the first and last node. A deque, or double-ended queue, allows push and pop at both ends and generalises the queue the way the standard libraries do.

C has no queue type in its standard library, so the C versions here are complete programs. C++ ships std::queue, an adaptor that wraps a std::deque by default and exposes only push, pop, front, back, empty and size. Java has the Queue interface, with ArrayDeque as the usual implementation. Python’s collections.deque and C#’s System.Collections.Generic.Queue<T> do the same job. Later sections measure what the wrappers cost and what each library does when a queue is empty.

A queue shows up wherever work must be handled in arrival order: a print spooler, the event loop of a graphical program, a network device’s transmit buffer, a thread pool’s task list, a producer and consumer exchanging messages, and every breadth-first search. Operating systems use FIFO queues too: a round-robin scheduler keeps runnable tasks in a ready queue, although general-purpose schedulers such as Linux’s order tasks by other rules and use other structures.

Two queue layouts: a node per item, or a ring of slots Linked queue: one node and one allocation per item 12 34 56 90 head tail Each node is 16 bytes, a value and a next pointer; the allocator rounds it to a 32-byte chunk. Ring queue, capacity 8: six items and two free slots 0 1 2 12 3 34 4 56 5 78 6 90 7 21 head tail (next write) After the last slot the next write wraps to slot 0. A count tells full from empty. The ring holds 8 ints in one allocation, used or not; the linked queue allocates only what it holds.
Figure 1: A linked queue stores one node, one pointer and one allocation per item; a ring queue stores a fixed number of slots in one allocation and reuses them as the head and the tail move round. The dashed arrow is the wrap from the last slot back to slot 0.

Queue Operations and Their Time Complexity

OperationWhat it doesGrowable circular arrayFixed ringSingly linked listDeque
pushAdds an item at the tailO(1) amortized; O(n) on the push that grows the arrayO(1); fails when fullO(1); one allocation per itemO(1) at either end
popRemoves and returns the front itemO(1)O(1)O(1); one deallocationO(1) at either end
frontReads the oldest item without removing itO(1)O(1)O(1)O(1)
backReads the newest itemO(1)O(1)O(1) with a tail pointerO(1)
emptyReports whether the queue holds nothingO(1)O(1)O(1)O(1)
sizeNumber of stored itemsO(1)O(1)O(1) if the list keeps a countO(1)
searchFinds an item by valueO(n)O(n)O(n)O(n)

The amortised entry is the only one that needs arithmetic. A growable ring doubles its capacity when full, so the pushes that trigger a resize get rarer at the same rate they get more expensive. Over a million pushes the block doubles at 8, 16, 32 and so on up to 1,048,576 slots, and the copy work adds up to 8 + 16 + … + 524,288 = 1,048,568 elements, about 1.05 moves per push. Growing by a fixed number of slots instead turns the total from linear into quadratic. The ring’s pop is O(1) regardless, because the removed slot is simply skipped by moving the head. Nothing shifts.

How This Was Measured

SettingValue
Date testedNovember 30, 2026
HardwareIntel Core i7-8700K, 6 cores and 12 threads at 3.70 GHz, 32 GB RAM, Windows 11 Education build 26300
Operating systemUbuntu 24.04.5 under WSL2, kernel 5.15.146, glibc 2.39; Windows 11 for the MSVC, Java and .NET builds
CompilersGCC 13.3 and Clang 18.1.3 at -O2 and -O3 through CMake Release; MSVC 19.44 at /W4 /WX
Language runtimesOpenJDK 27.0.1.1 (the CI matrix covers 17, 21 and 25); CPython 3.14.6; .NET SDK 10.0.404
Input1,000,000 sequential ints for the heap figures; a capacity-8 ring for the wrap checks; 100,000,000 push and pop pairs for the three ring designs; 5,000,000 pairs for the std::queue backends
What is timedThe push and pop calls, including the empty and full checks and the index arithmetic; the loop counter and the value generation are part of the timed region
StatisticMedian of 5 runs for every timing, in milliseconds; the heap figures are one run and are in bytes
CheckEvery timed program prints a checksum of the values it popped, and the checksum must match across the implementations being compared

No CPU pinning or frequency scaling control was used, and the host runs other software, so the millisecond figures are indicative for this machine and the ratios are the useful part. All timings come from one machine and one WSL2 instance. The Windows column of the verification table covers builds and tests, not timings. The heap figures belong to glibc’s allocator on Ubuntu and would move on another allocator, which is why the tests check queue behaviour rather than heap bytes.

Array or Linked List: Which Should Back a Queue?

The circular array stores the queue in one block. Two indices describe the state: head is the slot of the oldest item, and count is how many slots hold live items. The tail slot is computed as (head + count) % capacity, so no third index is stored and no slot is wasted. An empty queue has count zero. A full growable queue has count equal to capacity. The two states are different because the count differs even when head and the computed tail coincide.

The linked queue stores each item in a node with a pointer to the next node, and keeps two pointers, one to the oldest node and one to the newest. Push links a new node after the tail. Pop unlinks the head node and frees it. Nothing wraps, and the structure holds exactly as many nodes as there are items, plus a header for each allocation.

For int on x86-64 the difference in heap is large. This is the output of src/memory.c in the C repository, which pushes a million ints into each layout and asks glibc how much heap is in use:

Output:

sizeof(Node) = 16 bytes
array queue:  4199056 bytes for 1000000 ints (capacity 1048576)
linked queue: 32000000 bytes for 1000000 ints
ratio: 7.6x

The array’s figure includes the unused slots left over from the last doubling, and the linked queue still used 7.6 times as much heap. A 16-byte node took 32 bytes of heap, because the allocator stores a header and rounds the block up: the linked queue’s figure divided by a million gives 32 bytes per item. These figures belong to glibc on one machine, not to C, which is why the build does not assert them.

AspectGrowable circular arrayLinked queue
Heap for 1,000,000 ints, measured above4,199,056 bytes32,000,000 bytes
StorageOne contiguous blockOne heap allocation per item
Costliest pushThe one that doubles the blockEvery push costs one allocation
Unused spaceUp to half the block after a doubling, plus the head’s offsetNone beyond one pointer and the allocator header per item
Cache behaviourSequential within the block, good localityEach node is a separate allocation and a pointer chase
Allocation failurePossible only when growingPossible on every push
FreeingOne freeOne free per node, in a loop

For most programs the circular array is the better default. A linked queue earns its place when items are large and must not move in memory, when a push may not pay for a resize, or when nodes already exist for another structure. The choice mirrors the one between a dynamic array and a linked list, and the same measurements apply.

Heap for 1,000,000 ints: ring queue versus linked queue glibc heap in use, measured by mallinfo2, single-threaded ring queue 4,199,056 bytes one allocation, 1,048,576 slots linked queue 32,000,000 bytes 1,000,000 nodes plus allocator headers ratio: 7.6x more heap for the linked queue 4.20 bytes per int in the ring, 32.00 bytes per int in the linked nodes Figures from src/memory.c on Ubuntu 24.04, GCC 13.3, glibc 2.39.
Figure 2: One million ints cost 4,199,056 bytes of heap behind the ring queue and 32,000,000 bytes behind the linked queue on the test machine, a ratio of 7.6 times: the linked queue pays a node and an allocator header for every item.

Queue Implementation in C

C has no queue type in its standard library, so the three versions below are written from scratch. The listings show the data structure and its functions. The files in the repository add <stdbool.h>, <stddef.h>, <stdint.h> (for SIZE_MAX) and <stdlib.h>, plus the demo main. They store int. Changing the element type means changing the struct and the function signatures. The growable queue and the fixed ring share the same circular arithmetic, and the linked queue stores each item in a node.

The Growable Array Queue

typedef struct {
    int   *items;     /* heap block used as a ring: slot i sits at (head+i)%capacity */
    size_t head;      /* index of the oldest element                                */
    size_t count;     /* elements stored; the next free slot is head + count        */
    size_t capacity;  /* slots allocated                                            */
} ArrayQueue;

void aq_init(ArrayQueue *q)
{
    q->items = NULL;
    q->head = 0;
    q->count = 0;
    q->capacity = 0;
}

void aq_free(ArrayQueue *q)
{
    free(q->items);
    aq_init(q);
}

bool aq_empty(const ArrayQueue *q)
{
    return q->count == 0;
}

size_t aq_size(const ArrayQueue *q)
{
    return q->count;
}

/* Doubles the block and copies the elements in FIFO order. The copy is what
 * straightens a buffer whose elements have wrapped past the end. Returns
 * false if the new block cannot be allocated; the queue is unchanged. */
static bool aq_grow(ArrayQueue *q)
{
    if (q->capacity > SIZE_MAX / 2 / sizeof *q->items)
        return false;                      /* byte count would overflow */
    size_t new_capacity = q->capacity ? q->capacity * 2 : 8;
    int *items = malloc(new_capacity * sizeof *items);
    if (items == NULL)
        return false;                      /* old block is still valid  */
    for (size_t i = 0; i < q->count; ++i)
        items[i] = q->items[(q->head + i) % q->capacity];
    free(q->items);
    q->items = items;
    q->head = 0;
    q->capacity = new_capacity;
    return true;
}

/* Returns false if the queue could not grow; the queue is unchanged. */
bool aq_push(ArrayQueue *q, int value)
{
    if (q->count == q->capacity && !aq_grow(q))
        return false;
    q->items[(q->head + q->count) % q->capacity] = value;
    q->count++;
    return true;
}

/* Returns false on an empty queue and leaves *out untouched. */
bool aq_pop(ArrayQueue *q, int *out)
{
    if (q->count == 0)
        return false;
    *out = q->items[q->head];
    q->head = (q->head + 1) % q->capacity;
    q->count--;
    return true;
}

bool aq_front(const ArrayQueue *q, int *out)
{
    if (q->count == 0)
        return false;
    *out = q->items[q->head];
    return true;
}

Four details carry the correctness of this version:

  • count is a size_t and never goes negative. An empty queue is count == 0 and a full one is count == capacity, so the two states differ even when the head and the computed tail coincide.
  • The growth check runs before the multiplication: capacity > SIZE_MAX / 2 / sizeof *items stops the new byte count from wrapping on a 32-bit build.
  • The copy that grows the block walks the logical order with (head + i) % capacity, so a buffer whose items have wrapped past the end is straightened into one run starting at index 0.
  • malloc failure leaves the old block and the queue unchanged. The push returns false instead of losing items.

The tail slot is never stored. aq_push computes it as (head + count) % capacity at the moment of writing, which is why the struct needs three bookkeeping fields beside the pointer and not four. The block starts at 8 slots on the first push and doubles from there.

The Fixed-Capacity Ring Queue

typedef struct {
    int   *items;     /* heap block of capacity slots; capacity is slots, no gap */
    size_t head;      /* index of the oldest element                            */
    size_t count;     /* elements stored                                        */
    size_t capacity;  /* slots allocated                                        */
} RingQueue;

/* A ring needs at least one slot. Returns false if the block cannot be
 * allocated; the queue is left empty and safe to free. */
bool rq_init(RingQueue *q, size_t capacity)
{
    q->items = NULL;
    q->head = 0;
    q->count = 0;
    q->capacity = 0;
    if (capacity == 0 || capacity > SIZE_MAX / sizeof *q->items)
        return false;
    q->items = malloc(capacity * sizeof *q->items);
    if (q->items == NULL)
        return false;
    q->capacity = capacity;
    return true;
}

void rq_free(RingQueue *q)
{
    free(q->items);
    q->items = NULL;
    q->head = 0;
    q->count = 0;
    q->capacity = 0;
}

bool rq_full(const RingQueue *q)
{
    return q->count == q->capacity;
}

bool rq_empty(const RingQueue *q)
{
    return q->count == 0;
}

size_t rq_size(const RingQueue *q)
{
    return q->count;
}

bool rq_push(RingQueue *q, int value)
{
    if (q->count == q->capacity)
        return false;
    q->items[(q->head + q->count) % q->capacity] = value;
    q->count++;
    return true;
}

bool rq_pop(RingQueue *q, int *out)
{
    if (q->count == 0)
        return false;
    *out = q->items[q->head];
    q->head = (q->head + 1) % q->capacity;
    q->count--;
    return true;
}

bool rq_front(const RingQueue *q, int *out)
{
    if (q->count == 0)
        return false;
    *out = q->items[q->head];
    return true;
}

RingQueue takes its capacity at rq_init and allocates exactly that many slots. The capacity counts slots, not one less: a ring of capacity 8 holds 8 values, and rq_full is count == capacity. The other common design leaves one slot open and tests (tail + 1) % capacity == head. It holds only 7 values in 8 slots, and the experiment below compares the two designs, plus a third that keeps a flag. rq_init rejects a zero capacity and a byte count that would overflow, so the queue is either usable or empty and safe to free.

The Linked Queue

typedef struct LqNode {
    int            value;
    struct LqNode *next;
} LqNode;

typedef struct {
    LqNode *head;   /* oldest element, popped first         */
    LqNode *tail;   /* newest element, pushed last          */
    size_t  size;   /* nodes in the queue                   */
} LinkedQueue;

void lq_init(LinkedQueue *q)
{
    q->head = NULL;
    q->tail = NULL;
    q->size = 0;
}

bool lq_empty(const LinkedQueue *q)
{
    return q->head == NULL;
}

size_t lq_size(const LinkedQueue *q)
{
    return q->size;
}

/* Returns false if the node could not be allocated; the queue is unchanged. */
bool lq_push(LinkedQueue *q, int value)
{
    LqNode *node = malloc(sizeof *node);
    if (node == NULL)
        return false;
    node->value = value;
    node->next = NULL;
    if (q->tail == NULL)
        q->head = node;                    /* first node becomes head too */
    else
        q->tail->next = node;
    q->tail = node;
    q->size++;
    return true;
}

/* Returns false on an empty queue and leaves *out untouched. */
bool lq_pop(LinkedQueue *q, int *out)
{
    LqNode *node = q->head;
    if (node == NULL)
        return false;
    *out = node->value;
    q->head = node->next;
    if (q->head == NULL)
        q->tail = NULL;                    /* the queue is empty again    */
    free(node);
    q->size--;
    return true;
}

bool lq_front(const LinkedQueue *q, int *out)
{
    if (q->head == NULL)
        return false;
    *out = q->head->value;
    return true;
}

/* Iterative, so a million-node queue does not recurse a million deep. */
void lq_free(LinkedQueue *q)
{
    LqNode *node = q->head;
    while (node != NULL) {
        LqNode *next = node->next;
        free(node);
        node = next;
    }
    lq_init(q);
}

Push allocates a node, links it after the tail and makes it the tail. The first push sets both head and tail to that node. Pop copies the value out, unlinks the head node, frees it, and clears the tail when the queue becomes empty. lq_free walks the list with a loop, saving next before each free, so releasing a million-node queue needs no recursion. The test suite frees a million-node queue under LeakSanitizer.

The C Demo

The growable queue and the ring share one demo program. It pushes three values, reads the front, pops one, pushes another, drains the queue, and then repeats a shorter sequence on a capacity-8 ring that wraps:

Output:

growable array queue
push 10, 20, 30 -> front 10, size 3
pop -> 10, front 20
push 40 -> front 20, size 3
drain -> 20 30 40
empty -> true
ring queue, capacity 8
push 1 to 8 -> full true, size 8, front 1
pop -> 1, front 2, size 7
push 9 -> full true, size 8, front 2
drain -> 2 3 4 5 6 7 8 9
empty -> true

The ring section is the wrap check. After eight pushes the computed tail, (head + count) % capacity, has returned to slot 0 and the queue is full. One pop moves the head to slot 1, and pushing 9 writes into slot 0, the slot just behind the head. Draining then reads slots 1 to 7 and slot 0 in that order, which is why the last printed value is 9. The linked queue prints the same sequence from its own demo program:

Output:

linked queue
push 10, 20, 30 -> front 10, size 3
pop -> 10, front 20
push 40 -> front 20, size 3
drain -> 20 30 40
empty -> true

The five language versions print these bytes exactly. The demos are checked against the files in tests/expected/ on every build, so a change in wording or spacing fails the build rather than reaching the page.

Queue Implementation in C++

In C++ the growth and the memory of the C version come from the library. The three class templates below keep the same public shape as the C functions, with push, pop, front, empty and size, and add an exception for the empty case plus a try_pop for the callers that prefer a return value. The array-backed templates need an element type that is default-constructible and movable, because the buffer holds default-constructed slots. That still includes move-only types such as std::unique_ptr<int>. LinkedQueue<T> has no such requirement.

ArrayQueue: a Class Template Over a Vector

// array_queue.hpp - a growable FIFO queue in a circular array: a head index
// plus a count, and the buffer doubles when it fills.
#ifndef MYCPLUS_ARRAY_QUEUE_HPP
#define MYCPLUS_ARRAY_QUEUE_HPP

#include <cstddef>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>

template <typename T>
class ArrayQueue {
public:
    ArrayQueue() : buffer_(kInitialCapacity) {}

    ArrayQueue(const ArrayQueue&) = default;
    ArrayQueue& operator=(const ArrayQueue&) = default;

    // A moved-from queue is left empty and usable. The implicit move would
    // empty the vector but keep the old count, so empty() would lie.
    ArrayQueue(ArrayQueue&& other) noexcept
        : buffer_(std::exchange(other.buffer_, {})),
          head_(std::exchange(other.head_, 0)),
          count_(std::exchange(other.count_, 0)) {}

    ArrayQueue& operator=(ArrayQueue&& other) noexcept
    {
        if (this != &other) {
            buffer_ = std::exchange(other.buffer_, {});
            head_ = std::exchange(other.head_, 0);
            count_ = std::exchange(other.count_, 0);
        }
        return *this;
    }

    void push(const T& value)
    {
        ensure_room();
        buffer_[slot(count_)] = value;
        ++count_;
    }

    void push(T&& value)
    {
        ensure_room();
        buffer_[slot(count_)] = std::move(value);
        ++count_;
    }

    T pop()
    {
        require_non_empty("pop");
        T value = std::move(buffer_[head_]);
        head_ = (head_ + 1) % buffer_.size();
        --count_;
        return value;
    }

    T& front()             { require_non_empty("front"); return buffer_[head_]; }
    const T& front() const { require_non_empty("front"); return buffer_[head_]; }

    // Moves the oldest element into out. Returns false and leaves out untouched
    // when the queue is empty.
    bool try_pop(T& out)
    {
        if (count_ == 0)
            return false;
        out = std::move(buffer_[head_]);
        head_ = (head_ + 1) % buffer_.size();
        --count_;
        return true;
    }

    [[nodiscard]] bool empty() const noexcept { return count_ == 0; }
    std::size_t size() const noexcept { return count_; }

    void clear()
    {
        for (std::size_t i = 0; i < count_; ++i)
            buffer_[slot(i)] = T{};
        head_ = 0;
        count_ = 0;
    }

private:
    // The buffer holds default-constructed slots, and size() is the capacity.
    static constexpr std::size_t kInitialCapacity = 4;

    std::size_t slot(std::size_t offset) const noexcept
    {
        return (head_ + offset) % buffer_.size();
    }

    void ensure_room()
    {
        if (count_ < buffer_.size())
            return;
        const std::size_t new_capacity =
            buffer_.empty() ? kInitialCapacity : buffer_.size() * 2;
        std::vector<T> grown(new_capacity);
        for (std::size_t i = 0; i < count_; ++i)
            grown[i] = std::move(buffer_[slot(i)]);
        buffer_ = std::move(grown);
        head_ = 0;
    }

    void require_non_empty(const char* op) const
    {
        if (count_ == 0)
            throw std::out_of_range(std::string("ArrayQueue::") + op +
                                    " on an empty queue");
    }

    std::vector<T> buffer_;   // slots, not elements: size() is the capacity
    std::size_t head_ = 0;    // index of the oldest element
    std::size_t count_ = 0;   // number of stored elements
};

#endif

The buffer is a std::vector<T> sized to the capacity, not grown one element at a time, so buffer_.size() is the capacity and count_ is the number of live elements. The two push overloads let a caller move an element in without a copy. The move constructor and move assignment are written out because the compiler-generated versions would move the vector but copy count_, leaving a moved-from queue that claims to hold elements it no longer has.

pop returns the element by value, which is convenient and safe when moving a T cannot throw, as for int, std::string and std::unique_ptr. If a type’s move or copy constructor can throw, a value-returning pop can lose the element after it has left the queue. That is why std::queue splits the operation into front() and a pop() that returns nothing. try_pop is the alternative here: it moves the element into a variable the caller already owns and reports whether anything was there.

clear() writes T{} into every live slot instead of only resetting the indices. Without that loop, live elements such as strings or std::unique_ptr objects would stay alive in the buffer, holding their memory, until each slot happened to be overwritten. The growth step allocates a new vector, moves the elements in FIFO order through the same modulo arithmetic as the C version, and resets the head to 0. That reallocation is the pattern the guide to std::vector measures from the container side.

RingQueue and LinkedQueue

RingQueue<T> is the fixed-capacity variant: it takes the capacity in its constructor, sizes one vector to it, and returns false from push when full. Its capacity counts slots, so a queue built with 8 holds 8 values. A ring built with capacity 0 reports full at once and refuses every push, so it never divides by zero.

LinkedQueue<T> owns a chain of nodes through std::unique_ptr<Node> and keeps a non-owning raw pointer to the tail. Its destructor calls clear():

    // Unlinks one node at a time, so destroying a long queue does not recurse
    // once per node.
    void clear() noexcept
    {
        while (head_)
            head_ = std::move(head_->next);
        tail_ = nullptr;
        size_ = 0;
    }

A node that owns the next node through std::unique_ptr destroys the chain one link at a time, and each link is one nested destructor call. A long enough queue overflows the call stack. The stack article measures that crash for linked stacks. clear() unlinks from the head instead, so destroying a million-node queue uses constant stack space, and the test suite destroys and moves one of that size under AddressSanitizer. Copying is deleted because a queue rarely needs a deep copy, and move assignment calls clear() before taking the source’s nodes.

std::queue, the Standard Adaptor

For production C++, use std::queue from <queue>. It is not a container but an adaptor: it wraps a container and exposes push, emplace, pop, front, back, empty, size and swap (C++23 adds push_range). The default underlying container is std::deque. std::list also qualifies, because the adaptor needs front, back, push_back and pop_front. std::vector does not qualify: a std::queue<int, std::vector<int>> can be declared and pushed to, but the first call to pop() fails to compile because a vector has no pop_front.

Two behaviours need care. std::queue has no clear() and no iterators, so emptying it means popping in a loop (or assigning an empty queue), and a queue that needs to be inspected is the wrong choice. And front() or pop() on an empty queue is undefined behaviour: the adaptor does not check, and it forwards the call to the underlying container, whose front() and pop_front() also have an emptiness precondition. The pitfalls section captures what that looks like with libstdc++’s assertions enabled. The benchmark later in this article measures the difference between the deque and list backends.

The C++ Demo

// array_queue_demo.cpp - ArrayQueue<int> and RingQueue<int>: the growable
// circular queue and the fixed-capacity ring, printing the article's demo.
// Build: g++ -std=c++17 -Wall -Wextra -pedantic -Iinclude src/array_queue_demo.cpp -o array_queue_demo
#include <iostream>

#include "array_queue.hpp"
#include "ring_queue.hpp"

int main()
{
    std::cout << std::boolalpha;

    std::cout << "growable array queue\n";
    ArrayQueue<int> q;
    q.push(10);
    q.push(20);
    q.push(30);
    std::cout << "push 10, 20, 30 -> front " << q.front() << ", size "
              << q.size() << '\n';

    const int first = q.pop();
    std::cout << "pop -> " << first << ", front " << q.front() << '\n';

    q.push(40);
    std::cout << "push 40 -> front " << q.front() << ", size " << q.size()
              << '\n';

    std::cout << "drain ->";
    while (!q.empty()) {
        std::cout << ' ' << q.front();
        q.pop();
    }
    std::cout << '\n';
    std::cout << "empty -> " << q.empty() << '\n';

    RingQueue<int> ring(8);
    std::cout << "ring queue, capacity " << ring.capacity() << '\n';
    for (int value = 1; value <= 8; ++value)
        ring.push(value);
    std::cout << "push 1 to 8 -> full " << ring.full() << ", size "
              << ring.size() << ", front " << ring.front() << '\n';

    const int ring_first = ring.pop();
    std::cout << "pop -> " << ring_first << ", front " << ring.front()
              << ", size " << ring.size() << '\n';

    ring.push(9);
    std::cout << "push 9 -> full " << ring.full() << ", size " << ring.size()
              << ", front " << ring.front() << '\n';

    std::cout << "drain ->";
    while (!ring.empty()) {
        std::cout << ' ' << ring.front();
        ring.pop();
    }
    std::cout << '\n';
    std::cout << "empty -> " << ring.empty() << '\n';
}

The program prints exactly the C output above, and the build compares it against the same expected file. The ring section uses the same capacity-8 wrap, and the linked demo prints the linked output. The Java, Python and C# versions follow the same API and print the same bytes.

Queue Implementation in Java, Python and C#

The three versions that follow repeat the C design rather than the C++ one: a growable circular array with a head index and a count, a fixed ring, and a linked queue. Some details are language-specific and worth showing: how Java stores generics in an Object[], how Python needs no array at all until the queue fills, and how C# names its non-throwing variants.

Java

import java.util.NoSuchElementException;

/**
 * A growable FIFO queue in a circular array: a head index plus a count,
 * with the array doubled when it fills. Not thread-safe.
 */
public final class ArrayQueue<E> {
    private static final int INITIAL_CAPACITY = 8;
    // OpenJDK's conservative "soft maximum" array length: HotSpot can refuse
    // arrays closer to Integer.MAX_VALUE even when heap is available.
    private static final int MAX_CAPACITY = Integer.MAX_VALUE - 8;

    private Object[] items = new Object[INITIAL_CAPACITY];
    private int head;   // index of the front element
    private int count;  // number of stored elements

    /** Adds value at the tail. The array grows when it is full. */
    public void push(E value) {
        if (count == items.length) {
            grow();
        }
        items[physical(count)] = value;
        count++;
    }

    /** Removes and returns the front element. */
    public E pop() {
        E value = front();
        items[head] = null;   // drop the reference so the GC can reclaim it
        head = (head + 1) % items.length;
        count--;
        return value;
    }

    @SuppressWarnings("unchecked")   // only E values are ever stored
    public E front() {
        if (count == 0) {
            throw new NoSuchElementException("pop or front on an empty queue");
        }
        return (E) items[head];
    }

    public boolean isEmpty() {
        return count == 0;
    }

    public int size() {
        return count;
    }

    /**
     * Maps a logical offset (0 is the front) to an array index without
     * computing head + offset, which could overflow an int near MAX_CAPACITY.
     */
    private int physical(int offset) {
        int untilEnd = items.length - head;
        return offset < untilEnd ? head + offset : offset - untilEnd;
    }

    /** Doubles the array and copies the two wrapped runs into one run from index 0. */
    private void grow() {
        if (items.length == MAX_CAPACITY) {
            throw new IllegalStateException("queue is full");
        }
        int newLength = (int) Math.min(2L * items.length, MAX_CAPACITY);
        Object[] bigger = new Object[newLength];
        for (int i = 0; i < count; i++) {
            bigger[i] = items[physical(i)];
        }
        items = bigger;
        head = 0;
    }
}

Java cannot create an array of a type parameter, so the queue stores an Object[] and casts on the way out. Only push writes into the array, which the private field guarantees. pop() writes null into the vacated slot so the garbage collector can reclaim a popped object, a detail the stack article measures.

The doubling is computed in long arithmetic and capped at Integer.MAX_VALUE - 8, because an array near the maximum can be refused by the runtime even when there is room. The physical helper turns a logical position into an array index by subtraction rather than (head + i) % length, because head + i can exceed Integer.MAX_VALUE once the array is larger than about a billion slots.

The method names push, pop and front match the other languages on this page. The JDK’s own names differ: the Queue interface uses offer, poll and peek (which return false or null) and add, remove and element (which throw). Be careful with ArrayDeque.push and ArrayDeque.pop: they are stack operations that both work at the head, so a program that calls push and pop on an ArrayDeque gets last-in, first-out order, not a queue.

In application code, use java.util.ArrayDeque through the Queue interface, with offer and poll or add and remove. Its documentation states that most operations run in amortised constant time, that null elements are prohibited, and that the class is not thread-safe, so a shared queue needs ArrayBlockingQueue, ConcurrentLinkedQueue or an explicit lock. java.util.LinkedList also implements Queue, but it allocates a node per element, and the ArrayDeque documentation says the class is likely to be faster than LinkedList when used as a queue. ArrayDeque is also the class the deque section uses.

Python

A Python list is not a queue: append is O(1), but pop(0) and insert(0, x) move every other element and cost O(n). collections.deque is the queue for real code, with O(1) appends and pops at both ends. The class below matches the other languages and shows the circular arithmetic without the pop(0) cost:

from typing import Generic, TypeVar, cast

T = TypeVar("T")


class QueueUnderflowError(IndexError):
    """Raised by pop() or front() on an empty queue."""


class ArrayQueue(Generic[T]):
    """A growable circular array with a head index and a count.

    ``head`` marks the oldest element and ``count`` says how many slots hold
    live elements, so the queue is empty exactly when the count is 0 and full
    exactly when the count reaches the capacity.  The buffer doubles when a
    push finds it full.  Free slots hold None.
    """

    def __init__(self) -> None:
        self._items: list[T | None] = [None] * 8
        self._head = 0
        self._count = 0

    def _grow(self) -> None:
        """Double the buffer and copy the live elements in FIFO order."""
        old = self._items
        grown: list[T | None] = [None] * (2 * len(old))
        for offset in range(self._count):
            grown[offset] = old[(self._head + offset) % len(old)]
        self._items = grown
        self._head = 0

    def push(self, value: T) -> None:
        if self._count == len(self._items):
            self._grow()
        self._items[(self._head + self._count) % len(self._items)] = value
        self._count += 1

    def pop(self) -> T:
        if self._count == 0:
            raise QueueUnderflowError("pop from an empty queue")
        value = self._items[self._head]
        self._items[self._head] = None  # release the reference
        self._head = (self._head + 1) % len(self._items)
        self._count -= 1
        return cast(T, value)

    def front(self) -> T:
        if self._count == 0:
            raise QueueUnderflowError("front of an empty queue")
        return cast(T, self._items[self._head])

    def is_empty(self) -> bool:
        return self._count == 0

    def __len__(self) -> int:
        return self._count

ArrayQueue.pop() raises QueueUnderflowError, a subclass of IndexError, so code that already catches IndexError keeps working. Free slots hold None, and pop writes None back into the slot it empties. Without that line the list would keep a reference to every popped object until the slot was reused, and a queue of large objects would hold their memory long after the caller had finished with them. cast(T, ...) tells the type checker that a live slot never holds the placeholder. It costs nothing at run time. RingQueue is the same class with a fixed capacity and a push that returns False when full.

For threads, use queue.Queue from the standard library: its put and get take a lock and can block, and queue.SimpleQueue is the lighter version without task_done() or join(). For asyncio code, asyncio.Queue plays the same role.

C#

using System;

namespace MyCPlus.Queue;

/// <summary>A growable circular array queue. Not thread-safe.</summary>
public sealed class ArrayQueue<T>
{
    private T[] _items = new T[8];
    private int _head;    // index of the front element
    private int _count;

    public int Count => _count;
    public bool IsEmpty => _count == 0;

    public void Push(T value)
    {
        if (_count == _items.Length)
            Grow();
        _items[Physical(_count)] = value;
        _count++;
    }

    public T Pop()
    {
        T value = Peek();
        _items[_head] = default!;   // drop the reference so the GC can reclaim it
        _head = (_head + 1) % _items.Length;
        _count--;
        return value;
    }

    public bool TryPop(out T value)
    {
        if (_count == 0)
        {
            value = default!;
            return false;
        }
        value = Pop();
        return true;
    }

    public T Peek()
    {
        if (_count == 0)
            throw new InvalidOperationException("Pop or Peek on an empty queue.");
        return _items[_head];
    }

    public bool TryPeek(out T value)
    {
        if (_count == 0)
        {
            value = default!;
            return false;
        }
        value = _items[_head];
        return true;
    }

    // Doubling copies the queue in logical order, from the head through both
    // wrapped runs. Copying the buffer in physical order would rotate the
    // elements once the head has moved.
    private void Grow()
    {
        // Doubling in long arithmetic cannot wrap; Array.MaxLength caps it.
        int newLength = (int)Math.Min(2L * _items.Length, Array.MaxLength);
        if (newLength == _items.Length)
            throw new InvalidOperationException("Queue is full.");
        var grown = new T[newLength];
        for (int i = 0; i < _count; i++)
            grown[i] = _items[Physical(i)];
        _items = grown;
        _head = 0;
    }

    // Logical offset (0 is the front) to array index, without computing
    // _head + offset, which could overflow near Array.MaxLength.
    private int Physical(int offset)
    {
        int untilEnd = _items.Length - _head;
        return offset < untilEnd ? _head + offset : offset - untilEnd;
    }
}

The C# version follows the Java one: a doubling computed in long and capped at Array.MaxLength, the same overflow-safe Physical index helper, a slot cleared to default! on pop so the collector can reclaim a popped object, and a separate TryPop/TryPeek pair that returns false instead of throwing. The names Push and Pop keep the page consistent across languages. In .NET those are the Stack<T> names, and the library queue calls them Enqueue and Dequeue, so a production class should follow Queue<T>.

System.Collections.Generic.Queue<T> is the library version, and its documentation describes it as a circular array, the same layout as the class above. It offers TryDequeue and TryPeek beside the throwing methods and is not built for concurrent access. System.Collections.Concurrent.ConcurrentQueue<T> is the shared-access version. The .NET 10 base class library has no Deque<T>, which is why the deque section uses LinkedList<T> there.

Deque: A Queue With Two Ends

A deque, or double-ended queue, allows push and pop at both ends. A queue is the restricted deque that adds at one end and removes at the other, and a stack is the deque restricted to a single end. C++ has std::deque in the standard library; Java has ArrayDeque; Python has collections.deque; .NET has no deque type, and LinkedList<T> provides the same four operations at a per-node cost. C has no deque, and the ring queue from earlier is the starting point for one.

// deque_demo.cpp - std::deque as a double-ended queue, then the monotonic
// deque that answers sliding-window maximum in one pass.
// Build: g++ -std=c++17 -Wall -Wextra -pedantic src/deque_demo.cpp -o deque_demo
#include <cstddef>
#include <deque>
#include <iostream>
#include <vector>

// For every window of k values, keep the indices whose values are decreasing.
// The front of the deque is the index of the current window's maximum.
std::vector<int> sliding_window_max(const std::vector<int>& values, std::size_t k)
{
    std::vector<int> maxima;
    if (k == 0)
        return maxima;
    std::deque<std::size_t> candidates;
    for (std::size_t i = 0; i < values.size(); ++i) {
        while (!candidates.empty() && candidates.front() + k <= i)
            candidates.pop_front();                   // left the window
        while (!candidates.empty() && values[candidates.back()] <= values[i])
            candidates.pop_back();                    // not a maximum any more
        candidates.push_back(i);
        if (i + 1 >= k)
            maxima.push_back(values[candidates.front()]);
    }
    return maxima;
}

int main()
{
    std::deque<int> d;
    std::cout << "deque\n";

    d.push_front(2);
    d.push_back(3);
    std::cout << "push_front 2, push_back 3 -> front " << d.front()
              << ", back " << d.back() << ", size " << d.size() << '\n';

    d.push_front(1);
    d.push_back(4);
    std::cout << "push_front 1, push_back 4 -> front " << d.front()
              << ", back " << d.back() << ", size " << d.size() << '\n';

    const int front = d.front();
    d.pop_front();
    const int back = d.back();
    d.pop_back();
    std::cout << "pop_front -> " << front << ", pop_back -> " << back
              << ", size " << d.size() << '\n';

    const std::vector<int> values = {1, 3, -1, -3, 5, 3, 6, 7};
    const std::vector<int> maxima = sliding_window_max(values, 3);
    std::cout << "sliding window max, k = 3:";
    for (int value : maxima)
        std::cout << ' ' << value;
    std::cout << '\n';
}

The first half of the program is the plain deque: push_front(2), push_back(3), then push_front(1) and push_back(4), reading both ends and popping one value from each.

The second half answers a question a queue cannot: the maximum of every window of k values in an array. The function keeps indices, not values, in a deque whose values are strictly decreasing. The front index is the maximum of the current window.

For each new index, the loop pops indices from the back while their values are less than or equal to the new value, because a smaller value behind a larger one can never be the maximum while the larger one is in the window. An index leaves from the front when it falls out of the window. Each index enters once and leaves once, so the whole array costs O(n) instead of the O(nk) of testing every window separately.

Output:

deque
push_front 2, push_back 3 -> front 2, back 3, size 2
push_front 1, push_back 4 -> front 1, back 4, size 4
pop_front -> 1, pop_back -> 4, size 2
sliding window max, k = 3: 3 3 5 5 6 7

The first four lines show that a deque really has two ends: the same structure serves as a queue at the back and a stack at the front in the same run. The last line is the sliding-window result for the array 1, 3, -1, -3, 5, 3, 6, 7 with k = 3. The Java version uses ArrayDeque, the Python version uses collections.deque with appendleft and append, and the C# version uses LinkedList<T> with AddFirst and AddLast. All four print the same bytes, and each build compares them against its own expected file.

LanguageDouble-ended typeBackingNotes
C++std::deque<T>Fixed-size blocks plus a map of block pointers (typical implementations)O(1) at both ends; pushing at an end invalidates iterators but not references
Javajava.util.ArrayDeque<E>Resizable circular arrayO(1) at both ends; rejects null; not thread-safe
Pythoncollections.dequeDoubly linked blocks of slots (CPython)O(1) at both ends, O(n) in the middle; optional maxlen discards from the opposite end; appends and pops at either end are thread-safe
C#System.Collections.Generic.LinkedList<T>Doubly linked nodesO(1) at both ends; one node per item; no Deque<T> type in .NET 10
CnoneBuild one on the ringA ring with a decrementing head serves push_front in O(1)

Empty, Full and the Circular-Array Ambiguity

A linked queue has one empty state and no full state. A ring queue has two states that a single pair of indices cannot always tell apart, and it has to decide what a pop on an empty queue reports. Both questions have more than one correct answer, and the choices decide the API and a little of the memory layout.

What Happens When You Dequeue an Empty Queue?

The table below states what each API does, with the exception types the test suites assert and the captured messages where this article ran the code:

Language and callResult on an empty queue
C, aq_pop or lq_pop from this guideReturns false and leaves the output variable untouched
C++, std::queue<int>::front() or pop()Undefined behaviour; with -D_GLIBCXX_ASSERTIONS, abort with the libstdc++ assertion captured in the pitfalls section
C++, ArrayQueue<T>::pop() from this guideThrows std::out_of_range
Java, ArrayDeque.remove() (queue method)Throws java.util.NoSuchElementException
Java, ArrayDeque.poll() (queue method)Returns null
Python, collections.deque.popleft()Raises IndexError
Python, ArrayQueue.pop() from this guideRaises QueueUnderflowError, a subclass of IndexError
C#, Queue<T>.Dequeue()Throws System.InvalidOperationException
C#, Queue<T>.TryDequeue(out _)Returns false

Two designs recur across the libraries. Most raise an error from the removing call and offer a non-throwing variant as well: poll beside remove in Java, TryDequeue beside Dequeue in C#, try_pop beside pop in the C++ classes here. The C functions only have the non-throwing form, because C has no exceptions.

C++’s std::queue is the exception. It leaves the check to the caller, and forgetting it is undefined behaviour, which is why the pitfalls section captures the assertion that libstdc++ adds for it. A hand-written queue should follow the language’s convention: a return value in C, an exception and a try_ variant in C++ and C#, null from the non-throwing methods in Java.

Three Ways to Tell Empty From Full

With a head and a tail index and nothing else, a ring queue is empty when the two are equal and full when the two are equal. The table lists three correct designs that add different state to break the tie, then the broken one:

DesignStored stateSlots a ring of 8 holdsFull testEmpty testCost
CountHead, count, capacity; the tail is computed8count == capacitycount == 0No wasted slot, size in O(1)
One slot openHead, tail, capacity7(tail + 1) % capacity == headtail == headOne slot always empty; size is (tail + capacity - head) % capacity
Full flagHead, tail, capacity, flag8tail == head && fulltail == head && !fullOne extra field to keep in step; size needs a branch on the flag
NothingHead, tail, capacityAmbiguousNot detectabletail == headThe queue silently loses its state

The count design is what the growable queue and the ring in this article use. It stores one field where the one-slot design stores another, as the aside explains, and it reads size() straight from a field instead of computing it from two indices. A fourth correct design, common in systems code, lets head and tail grow without wrapping and masks them with a power-of-two capacity. It belongs to ring buffers rather than to the queue as a data type.

/* The broken design: head and tail only. Full and empty both mean head == tail. */
typedef struct {
    int   *items;
    size_t capacity;
    size_t head;
    size_t tail;
} BrokenRing;

static bool broken_init(BrokenRing *q, size_t capacity)
{
    q->items = malloc(capacity * sizeof *q->items);
    if (q->items == NULL)
        return false;
    q->capacity = capacity;
    q->head = 0;
    q->tail = 0;
    return true;
}

static void broken_free(BrokenRing *q)
{
    free(q->items);
}

static bool broken_push(void *self, int value)
{
    BrokenRing *q = self;
    q->items[q->tail] = value;
    q->tail = (q->tail + 1) % q->capacity;
    return true;
}

static bool broken_pop(void *self, int *out)
{
    BrokenRing *q = self;
    if (q->head == q->tail)
        return false;                      /* a full ring looks empty */
    *out = q->items[q->head];
    q->head = (q->head + 1) % q->capacity;
    return true;
}

static bool broken_empty(const void *self)
{
    const BrokenRing *q = self;
    return q->head == q->tail;
}

That broken ring stores a value at every push and advances the tail with % capacity. It never checks whether the ring is full, and its empty test is head == tail. After four pushes into a capacity-4 ring both indices have returned to 0, so the queue reports empty while four values are stored, and a fifth push would overwrite the oldest value without any error. Writing the arithmetic from memory without deciding the full case produces exactly this shape. The fix is one extra field, or one slot left open.

The experiment program runs the three correct designs side by side, then times them over 100,000,000 push and pop pairs with a capacity-1024 ring:

Output:

count:         drained 1 2 3 4 5, empty true
one-slot-open: drained 1 2 3 4 5, empty true, holds 7 of capacity 8
flag:          drained 1 2 3 4 5, empty true
broken ring:   capacity 4, 4 pushes -> empty true, pop -> false
100,000,000 push + pop pairs, median of 5 runs (ms)
count          1427
one-slot-open  1317
flag           1363
checksum: 51149901696

The correctness lines show the three designs agreeing on the order: each drains 1 2 3 4 5 and reports empty. The one-slot design then fills until it refuses, after 7 values in 8 slots, while the counting and flag designs hold the full 8. The broken ring reports empty after four pushes and refuses the pop.

The three timings came out within 8.4% of the fastest: 1,317 ms for the one-slot design, 1,363 ms for the flag and 1,427 ms for the count, over 100,000,000 push and pop pairs, or about 13 to 14 ns per pair. The one-slot design was fastest in this run, but a gap of under 9% from medians on one unpinned machine is too small to choose a design on, so the choice between them is about memory and simplicity, not throughput. The checksum confirms that all three popped the same values. The counting design wins on simplicity: no wasted slot, no separate full state, and the size is a field.

std::queue on a Deque and on a List

std::queue accepts any container with front, back, push_back and pop_front, and its default is std::deque. The backend is not a detail when a queue holds millions of items: a deque allocates a block of elements at a time, while a list allocates one node per element and adds a pointer pair to each. The benchmark program pushes and pops 5,000,000 values through each backend, then measures the heap while a queue of 1,000,000 ints is alive:

Output:

std::queue<int>, 5,000,000 push + pop pairs, median of 5 runs (ms)
deque backend  10.2
list backend   90.5
heap while holding 1,000,000 ints (bytes)
deque backend  4294400
list backend   32000016
checksum: 10732899603364764

The deque backend was 8.9 times faster on this machine, 10.2 ms against 90.5 ms for 5,000,000 pairs, and it used 4,294,400 bytes against 32,000,016 while holding the same million ints, a ratio of 7.5. The list pays a node allocation and a free per pair, and its nodes are scattered across the heap. The deque reuses the block it has and touches memory in longer runs.

std::list keeps references and iterators valid when other elements are removed, so it has a place when those references must survive, but for a plain FIFO queue the deque default is the right choice. The same allocation difference separates Java’s ArrayDeque from LinkedList, which is why the Java section recommends the array-backed one. This article did not time the Java pair.

Four Ways a Queue Passes a Quick Test and Still Fails

Each of these programs compiles without a warning under -Wall -Wextra -pedantic, and each would pass a quick test that never reaches the failing state. The first three live in the C repository’s pitfalls/ directory and the fourth in the C++ repository’s. The C directory also holds no_count.c, the broken ring from the previous section. The workflows rebuild each program and check the line of output or the sanitizer report that shows the bug.

1. Growing a Wrapped Buffer in Physical Order

/* The bug: items[0..count-1] is the physical layout, not the FIFO order.
 * The elements that wrapped past the end belong after the ones before them. */
static bool queue_grow(WrappedQueue *q)
{
    size_t new_capacity = q->capacity * 2;
    int *items = malloc(new_capacity * sizeof *items);
    if (items == NULL)
        return false;
    for (size_t i = 0; i < q->count; ++i)
        items[i] = q->items[i];
    free(q->items);
    q->items = items;
    q->head = 0;
    q->capacity = new_capacity;
    return true;
}

The copy loop walks the physical block from index 0, but the logical order starts at head and jumps from the last slot back to slot 0. Once the head has moved, a physical copy rotates the elements. The program pushes 12 values through a capacity-8 ring, forces one growth, and drains:

Output:

wrapped_growth: capacity 8, 12 pushes around the wrap
drain -> 9 10 11 4 5 6 7 8 12
FIFO order should have been 4 5 6 7 8 9 10 11 12
empty -> true

The drain reads 9, 10 and 11 before 4, because those three had wrapped to the front of the old block. A test that pushes and pops a handful of values before wrapping never reaches this state. The growth-after-wrap case in the test suite compares the drain against a model array and fails on this bug.

2. Forgetting the Wrap in the Tail Index

int main(void)
{
    Ring q;
    q.items = malloc(CAPACITY * sizeof *q.items);
    if (q.items == NULL) {
        fputs("out of memory\n", stderr);
        return EXIT_FAILURE;
    }
    q.tail = 0;

    printf("missing_modulo: pushing %d ints into capacity %d\n",
           CAPACITY + 1, CAPACITY);
    fflush(stdout);
    for (int value = 1; value <= CAPACITY + 1; ++value) {
        q.items[q.tail] = value;           /* tail never wraps: value 9 */
        q.tail++;                          /* writes items[8]            */
    }

    free(q.items);
    return EXIT_SUCCESS;
}

The loop stores at items[tail] and increments tail with no modulo. The ninth push into a capacity-8 block writes four bytes past the end. The build with -Wall -Wextra gave no warning: the block is heap-allocated, and compile-time bounds warnings catch only a few such writes, so this one is left to a run-time tool. AddressSanitizer reports the write:

Output (summarized from the AddressSanitizer report):

AddressSanitizer: heap-buffer-overflow
WRITE of size 4 at missing_modulo.c:33
0 bytes after a 32-byte region allocated at missing_modulo.c:22

Without a sanitizer the write lands in whatever allocation follows the block, so the program can print plausible output and corrupt the heap at the same time. The wrap is one % in the index calculation, and the compiler cannot add it for you.

3. A Sentinel Value That Means Empty

static int ring_pop(SentinelRing *q)
{
    if (q->count == 0)
        return EMPTY;
    int value = q->items[q->head];
    q->head = (q->head + 1) % CAPACITY;
    q->count--;
    return value;
}

Returning -1 from an empty pop is convenient until the queue stores -1. The program pushes the sentinel itself and then pops twice:

Output:

empty_sentinel: pop returns -1 for an empty queue
stored -1: pop -> -1, empty now true
empty queue: pop -> -1
cannot tell the two apart: true

Both calls return the same value, and the caller has no way to tell the stored element from the empty signal. Returning a bool and writing through an out parameter, or returning a value plus an optional, keeps the two cases separate. This is why the C functions in this article return bool and leave the output variable untouched on failure.

4. Trusting std::queue on an Empty Queue

// empty_std_queue.cpp - DO NOT COPY. std::queue::front() after the last pop().
// front() forwards to front() on the underlying container, and front() on an
// empty container is undefined behaviour. Build with -D_GLIBCXX_ASSERTIONS to
// turn it into a checked abort on libstdc++.
#include <iostream>
#include <queue>

int main()
{
    std::queue<int> q;
    q.push(42);
    const int first = q.front();
    q.pop();                                   // q is now empty
    std::cout << "first = " << first << ", empty = " << std::boolalpha
              << q.empty() << ", front = " << q.front() << '\n';
}

std::queue does not check for emptiness: front() forwards to the underlying container’s front(), and calling that on an empty container is undefined behaviour. Built with -D_GLIBCXX_ASSERTIONS, libstdc++ aborts with stl_queue.h:235: std::queue<int>::front(): Assertion '!this->empty()' failed. Without the macro the program is undefined behaviour, and it may print a plausible stale value. Test empty() before calling front() or pop(), and use the checked macro in debug builds as the stack article does.

Key Takeaways

  • A queue is FIFO: push at the tail, pop at the front, and every operation is O(1), amortised for the push that grows an array.
  • The circular array and the linked queue stored the same million ints in 4,199,056 and 32,000,000 bytes on the test machine, a ratio of 7.6.
  • A ring queue needs a count, a spare slot or a full flag to distinguish empty from full. The count keeps all slots usable and makes size() a field read.
  • The three correct designs timed within 8.4% of the fastest over 100,000,000 pairs, so the count is the choice for simplicity rather than for speed.
  • std::queue over std::deque was 8.9 times faster than over std::list and used about a seventh of the heap on this machine. The deque default suits a FIFO queue.
  • Growing a wrapped ring must copy the two runs in FIFO order. Copying the physical buffer rotates the queue and still passes a short test.
  • A deque adds O(1) operations at both ends, and the monotonic-deque sliding window is O(n) against O(nk) for the nested loop.

Frequently Asked Questions

Conclusion

The queue is small enough to write in an afternoon, and most of the difficulty is in the states rather than in the operations. The circular array needs one extra field to tell full from empty, the linked queue needs a tail pointer that is cleared when the last item leaves, and the standard adaptors leave the empty check to the caller. Each of those decisions appeared here as a captured message or a measured number rather than as a warning in prose.

In production code, use the library: std::queue over its deque default, ArrayDeque in Java, collections.deque in Python and Queue<T> in C#, with a hand-written circular array as the reasonable choice in C or when the ring is part of a larger structure. The data structures hub lists the structures that build on this one, from the circular buffer to the graph traversal.

Source Code and Tests

All programs on this page are in the data-structures/queue directory of the five MYCPLUS example repositories:

LanguageRepository directoryBuild status
Cmycplus/c-examples: data-structures/queueC queue build status
C++mycplus/cpp-examples: data-structures/queueC++ queue build status
Javamycplus/java-examples: data-structures/queueJava queue build status
Pythonmycplus/python-examples: data-structures/queuePython queue build status
C#mycplus/csharp-examples: data-structures/queueC# queue build status

The C and C++ examples build and test with CMake:

cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure

Java runs with javac --release 17 -Xlint:all -Werror -d build src/*.java tests/*.java followed by java -ea -cp build QueueTest; Python with python -m unittest discover -s tests -v; C# with dotnet build Queue.slnx -c Release followed by dotnet run --project tests/QueueTests -c Release --no-build.

What the builds check. Every demo’s stdout is compared byte for byte with the files in tests/expected/, so the output on this page is the output the build produces. The tests check both array queues against a model over 200,000 random operations in C and 100,000 in C++, the wrap and the growth-after-wrap order, the empty cases and a queue of 1,000,000 elements.

The C and C++ workflows also run the tests and demos under AddressSanitizer and UndefinedBehaviorSanitizer, and the C workflow re-runs each pitfall and checks the line of output or the sanitizer report that shows the bug. The builds do not check the heap figures or the timings: those belong to one machine and one allocator.

What I Verified

The example directories contain the test programs and the captured runs. The table states which system ran each check.

CheckUbuntu 24.04 (WSL2)Windows 11 (MSVC)
Build and tests, C, GCC 13.3Pass (7 of 7 tests)Not applicable
Build and tests, C, Clang 18.1.3Pass (7 of 7 tests)Not applicable
Build and tests, C, MSVC 19.44 /W4 /WXNot applicablePass (7 of 7 tests)
Build and tests, C++, g++ 13.3Pass (5 of 5 tests)Not applicable
Build and tests, C++, clang++ 18.1.3Pass (5 of 5 tests)Not applicable
Build and tests, C++, MSVC 19.44 /W4 /WX /permissive-Not applicablePass (4 of 4 tests; the benchmark is Linux only)
Java tests, JDK 21 on Ubuntu and JDK 27 on WindowsPass (all tests, three demo diffs)Pass (all tests, three demo diffs)
Python tests (3.12.3 on Ubuntu, 3.14.6 on Windows), ruff and mypy --strictPass (26 tests, three demo diffs, ruff and mypy clean)Pass (26 tests, three demo diffs, ruff and mypy clean)
.NET 10.0.404 build and testsNot runPass (all tests, three demo diffs)
AddressSanitizer and UndefinedBehaviorSanitizer, C and C++ tests and demosPass (C and C++ tests and demos)Not applicable
Four pitfalls, each caught by the check named in its sectionPass (3 output checks, 1 AddressSanitizer report)Not applicable
Heap and timing experimentsRun on Ubuntu 24.04, figures in the sections aboveNot run

Not covered: 32-bit builds, compilers newer than GCC 13.3 and Clang 18.1.3, Java 17 and 25 locally (the CI matrix covers them), macOS, and timings on any other machine.

Scroll to Top