SystemVerilog Reference

Queue Methods

A queue is a variable-size list. It grows and shrinks at both ends in constant time.

Syntax

int q[$];              // unbounded queue
q.push_back(5);        // add at the end
x = q.pop_front();     // remove from the start
n = q.size();

Rules

  • push_back and push_front add one item.
  • pop_back and pop_front remove one item and return it.
  • insert(i, v) and delete(i) work at index i. delete() with no index empties the queue.
  • q[0] is the first item and q[$] is the last.
  • Popping an empty queue returns the default value and may print a warning. Check size() first.

Example

module tb;
  int q[$];
  int x;

  initial begin
    q.push_back(10);
    q.push_back(20);
    q.push_front(5);
    $display("size=%0d first=%0d last=%0d", q.size(), q[0], q[$]);
    x = q.pop_front();
    $display("popped=%0d size=%0d", x, q.size());
    q.insert(1, 15);
    $display("q[0]=%0d q[1]=%0d q[2]=%0d", q[0], q[1], q[2]);
    q.delete();
    $display("size=%0d", q.size());
  end
endmodule
Output on Icarus Verilog 12
size=3 first=5 last=20
popped=5 size=2
q[0]=10 q[1]=15 q[2]=20
size=0

Run It in the Playground

Common Mistake

Deleting while looping by index

foreach (q[i])
  if (q[i] == 0) q.delete(i);   // skips the item after each delete

After a delete, the next item moves into index i. The loop then steps past it.

Fix: Loop from the last index down to 0, or build a new queue with q.find with (item != 0).

Learn It Properly

These lessons teach it step by step, with practice problems.

Standard

IEEE 1800-2023, 7.10.