Dynamic Arrays & Queues
Arrays whose size is chosen at run time, and queues that grow and shrink at both ends — the workhorses of testbench code.
Testbenches rarely know in advance how much data they will handle: a packet's payload length is random, a scoreboard holds however many transactions are in flight. Dynamic arrays and queues hold a variable number of elements and are used everywhere in verification code. They are simulation-only.
When to use which
int d[]; d[0] = 5; // run-time error: size is 0 int d[]; d = new[4]; d[0] = 5;
A dynamic array has no elements until it is allocated with new[].
int v = q.pop_front(); // q may be empty if (q.size() > 0) v = q.pop_front();
Popping an empty queue returns the default value and produces a warning: the testbench silently reads a 0. Check the size first.
How do you resize a dynamic array to 10 elements while keeping its contents?
d = new[10](d); — the second set of parentheses copies the old array into the new one.
How do you read the last element of a queue without removing it?
q[$] (or q[q.size()-1]).