Consider that a class already has well-written constraints, and there's a need to randomize the class variables with a different set of constraints, decided by the user. Using the with construct, you can declare inline constraints at the point randomize() is called. These additional constraints are considered alongside the object's original constraints by the solver — not instead of them.
10 min read | Intermediate Level
What You'll Learn
- What an inline constraint is, and why it's applied on top of a class's existing constraints rather than replacing them
- What happens when an inline constraint and an existing class constraint are genuinely incompatible
- Why inline constraints can never override an existing constraint, only add to it
- When
constraint_mode()is the right tool instead, if a constraint actually needs to be replaced rather than added to
Basic Inline Constraint
class Item;
rand bit [7:0] id;
constraint c_id { id < 25; }
endclass
module tb;
initial begin
Item itm = new ();
itm.randomize() with { id == 10; }; // In-line constraint using with construct
$display ("Item Id = %0d", itm.id);
end
endmodule
The inline constraint has been applied here, and the randomized id is 10:
run -all; # KERNEL: Item Id = 10 # KERNEL: Simulation has finished. There are no more test vectors to simulate.
This works because id == 10 and id < 25 are both true at once — the solver has no trouble satisfying both simultaneously.
Quick Check
Q: Would itm.randomize() with { id == 30; }; succeed against this same class?
Show Answer
No. Even though 30 is a perfectly legal 8-bit value on its own, it violates c_id's id < 25 requirement — an inline constraint still has to coexist with everything the class already declares, not just be valid in isolation.
When Inline and Class Constraints Conflict
If the original constraint fixes id to a single value, and the inline constraint asks for something incompatible, randomization fails:
class Item;
rand bit [7:0] id;
constraint c_id { id == 25; }
endclass
module tb;
initial begin
Item itm = new ();
if (! itm.randomize() with { id < 10; })
$display ("Randomization failed");
$display ("Item Id = %0d", itm.id);
end
endmodule
Output
ncsim> run
if (! itm.randomize() with { id < 10; })
|
ncsim: *W,SVRNDF (./testbench.sv,10|22): The randomize method call failed.
Observed simulation time : 0 FS + 0
ncsim: *W,RNDOCS: These constraints contribute to the set of conflicting constraints:
constraint c_id { id == 25; }; (./testbench.sv,4)
if (! itm.randomize() with { id < 10; }) (./testbench.sv,10)
ncsim: *W,RNDOCS: These variables contribute to the set of conflicting constraints:
rand variables:
id [./testbench.sv, 2]
Randomization failed
Item Id = 0
ncsim: *W,RNQUIE: Simulation is complete.
id can't simultaneously equal exactly 25 and be less than 10 — the solver correctly reports failure, and id is left at its stale default value, 0, rather than any value that actually satisfied either constraint.
The same failure happens even when both sides try to pin id to specific, individually valid values:
...
if (! itm.randomize() with { id == 10; })
...
Output
ncsim> run
if (! itm.randomize() with { id == 10; })
|
ncsim: *W,SVRNDF (./testbench.sv,10|22): The randomize method call failed.
Observed simulation time : 0 FS + 0
ncsim: *W,RNDOCS: These constraints contribute to the set of conflicting constraints:
constraint c_id { id == 25; }; (./testbench.sv,4)
if (! itm.randomize() with { id == 10; }) (./testbench.sv,10)
ncsim: *W,RNDOCS: These variables contribute to the set of conflicting constraints:
rand variables:
id [./testbench.sv, 2]
Randomization failed
Item Id = 0
ncsim: *W,RNQUIE: Simulation is complete.
Even though id == 10 would be a perfectly legal value all on its own, c_id still requires exactly 25 — and a variable can't equal two different specific values at the same time.
Quick Check
Q: If c_id were changed to id inside {20, 25, 30}; (a set of 3 legal values) and the inline constraint were id == 25;, would this succeed?
Show Answer
Yes. 25 is one of the values c_id already permits, so both constraints agree — there's no conflict, since id = 25 genuinely satisfies both requirements at once.
Inline Constraints Add To, Never Replace
The takeaway from both failing examples: constraints provided inline don't override the class's original constraints — they're considered alongside them by the solver, as an addition, not a replacement. If a class constraint is genuinely incompatible with what a specific test needs, an inline constraint can never fix that on its own; the original constraint has to be disabled first, using constraint_mode():
// If a test genuinely needs to REPLACE c_id rather than add to it:
itm.c_id.constraint_mode(0); // disable the original constraint first
itm.randomize() with { id < 10; }; // now this alone governs id
itm.c_id.constraint_mode(1); // re-enable it afterward, if needed
Where Is This Used?
Inline constraints are commonly used in individual test cases to steer a shared, reusable transaction class toward one specific scenario, without writing an entirely new subclass just for that test. As this article shows, that only works cleanly when the desired value is still compatible with the class's own built-in rules — a genuinely incompatible override needs constraint_mode() instead.
Common Beginner Mistakes
Mistake #1: Assuming an inline constraint can override an existing class constraint
As both conflict examples show, it can't — it only adds to what's already there. Why? A genuinely incompatible inline value doesn't replace the class's rule; it just makes the overall constraint set impossible to satisfy, and the whole call fails.
Mistake #2: Not checking randomize()'s return value with an inline constraint
The same general risk applies here as anywhere else, but it's easy to underestimate with inline constraints specifically. Why? It's simple to write an inline value that looks perfectly reasonable on its own while forgetting about a class constraint declared elsewhere that quietly conflicts with it.
Mistake #3: Assuming a failed randomize() leaves an obviously invalid value
As both examples show, id lands on 0 after the failure — not some clearly-invalid sentinel value that would be easy to notice. Why? Zero can easily look like a legitimate value if you're not specifically checking the return value, making a silent failure even easier to miss.
Mistake #4: Reaching for an inline constraint to disable a rule entirely
An inline constraint can't turn off an existing class constraint — only constraint_mode(0) can. Why? If the actual goal is to bypass a rule completely for one test, rather than add a compatible extra condition, inline constraints are the wrong tool for that specific job.
Practice Exercise
Challenge: Predict Two Inline Calls
Given constraint c_range { val inside {[10:20]}; }, predict whether each of these inline calls succeeds: randomize() with { val == 15; } and randomize() with { val == 25; }.
Hint
Check each inline value against c_range's own allowed range — the inline constraint still has to coexist with it, not just be a reasonable value on its own.
Solution
val == 15 succeeds — 15 falls within [10:20], so both constraints agree. val == 25 fails — 25 is outside c_range's allowed window, so no value can satisfy both requirements at once, and the call returns 0 with val left at its stale prior value.
Summary
In this tutorial, you learned:
- An inline constraint, added via
randomize() with { ... }, is considered alongside a class's existing constraints, not instead of them - If the inline constraint and an existing class constraint can't both be true at once,
randomize()fails and returns 0 - A failed randomization leaves the variable at its stale prior value — not a distinctly invalid one, making the return value the only reliable way to detect the failure
- Inline constraints can never override or disable an existing class constraint — that requires
constraint_mode(0)instead
Variables declared rand or randc inside a class aren't randomized automatically — you always call the built-in randomize() method to do it, and it returns 1 on success or 0 on failure. Two callback functions, pre_randomize() and post_randomize(), let you hook into that process to run your own code immediately before and after the solver assigns new random values.
6 min read | Intermediate Level
What You'll Learn
- How to call the built-in
randomize()method and check its return value - When
pre_randomize()andpost_randomize()run relative torandomize() - How overriding these two callbacks changes an object's randomization behavior
- What happens to
post_randomize()whenrandomize()fails
Calling randomize()
Class objects are not randomized automatically — you always have to call the built-in randomize() method yourself. It can fail for a variety of reasons, such as conflicting constraints or a solver that simply can't find a value satisfying every constraint at once, so the method returns a status you can check.
virtual function int randomize ();
Here's a simple example showing how randomize() is called:
class Beverage;
rand bit [7:0] beer_id;
constraint c_beer_id { beer_id >= 10;
beer_id <= 50; };
endclass
module tb;
Beverage b;
initial begin
b = new ();
$display ("Initial beerId = %0d", b.beer_id);
if (b.randomize ())
$display ("Randomization successful !");
$display ("After randomization beerId = %0d", b.beer_id);
end
endmodule
Output
run -all; # KERNEL: Initial beerId = 0 # KERNEL: Randomization successful ! # KERNEL: After randomization beerId = 25 # KERNEL: Simulation has finished. There are no more test vectors to simulate.
beer_id starts out at its default value of 0, then randomize() assigns it a fresh value between 10 and 50 as required by c_beer_id, and the if check confirms the call succeeded before printing the result. There are also two callback functions that randomize() automatically calls for you — one right before it computes random values, and one right after.
pre_randomize(): Running Code Before Randomization
This function is defined within the same class whose object will be randomized, and is called before the solver assigns random values.
function void pre_randomize();
We'll add a pre_randomize() function to the example discussed earlier, using the same testbench:
class Beverage;
rand bit [7:0] beer_id;
constraint c_beer_id { beer_id >= 10;
beer_id <= 50; };
function void pre_randomize ();
$display ("This will be called just before randomization");
endfunction
endclass
Output
run -all; # KERNEL: Initial beerId = 0 # KERNEL: This will be called just before randomization # KERNEL: Randomization successful ! # KERNEL: After randomization beerId = 25 # KERNEL: Simulation has finished. There are no more test vectors to simulate.
post_randomize(): Running Code After Randomization
This function is also defined within the same class, and is called after the solver has finished assigning random values.
function void post_randomize();
We'll add a post_randomize() function to the same example:
class Beverage;
rand bit [7:0] beer_id;
constraint c_beer_id { beer_id >= 10;
beer_id <= 50; };
function void pre_randomize ();
$display ("This will be called just before randomization");
endfunction
function void post_randomize ();
$display ("This will be called just after randomization");
endfunction
endclass
Output
run -all; # KERNEL: Initial beerId = 0 # KERNEL: This will be called just before randomization # KERNEL: This will be called just after randomization # KERNEL: Randomization successful ! # KERNEL: After randomization beerId = 25 # KERNEL: Simulation has finished. There are no more test vectors to simulate.
The order in the output tells the whole story: pre_randomize() runs first, then the solver assigns beer_id, then post_randomize() runs, and only after all of that does b.randomize() actually return — which is why "Randomization successful !" prints last, even though it's the first line of code inside the if.
Quick Check
Q: During a single call to randomize(), in what order do pre_randomize(), the constraint solver, and post_randomize() run?
Show Answer
pre_randomize() runs first, then the solver assigns random values to the object's rand/randc properties, and post_randomize() runs last — but only if the solve succeeded.
Overriding the Callbacks
What we did above is override the existing, empty pre_randomize() and post_randomize() methods with our own definitions — a clean way to change an object's randomization behavior without touching randomize() itself. If a class is derived from a base class and doesn't define its own version of either method, both automatically call their super version instead.
pre_randomize() and post_randomize() are not declared virtual, but they behave as if they were. If you try to make them virtual yourself, you'll hit a compiler error:
class Beverage;
rand bit [7:0] beer_id;
virtual function void pre_randomize ();
$display ("This will be called just before randomization");
endfunction
endclass
Output
virtual function void pre_randomize ();
|
ncvlog: *E,CLSMNV (testbench.sv,7|36): The pre_randomize() method cannot be declared virtual.
- If
randomize()fails,post_randomize()is not called - The
randomize()method itself is built-in and cannot be overridden - If randomization fails, the variables retain their original values and are not modified
Where Are pre_randomize() and post_randomize() Used?
pre_randomize() is handy for setting up values that a constraint depends on right before the solve runs, such as adjusting a range based on the current test phase. post_randomize() is more commonly used to fix up fields that are easier to compute after the randomized values exist — recalculating a checksum or parity bit over an already-randomized packet, or logging the final randomized values for debug.
Common Beginner Mistakes
Mistake #1: Expecting post_randomize() to run even when randomize() fails
post_randomize() only runs after a successful solve. Why? If the constraints couldn't be satisfied, there's no new random data to act on, so any cleanup logic you put in post_randomize() (like a checksum update) would be operating on unchanged, possibly stale values — SystemVerilog skips the call entirely instead.
Mistake #2: Manually declaring pre_randomize() or post_randomize() as virtual
Both callbacks already behave like virtual methods without the keyword. Why? The virtual keyword is reserved for methods you declare it on yourself; since these two are built-in overridable hooks, adding virtual explicitly is a compile-time error, not just a style issue.
Mistake #3: Assuming every class needs its own pre_randomize()/post_randomize()
Both methods have empty built-in default implementations, so you only define them when you actually need custom behavior. Why? A derived class that skips its own override doesn't lose functionality — it automatically falls back to calling the base class's version through super.
Practice Exercise
Challenge: Compute a Checksum in post_randomize()
Extend the Beverage class with a second field, bit [7:0] checksum, that is not declared rand. In post_randomize(), set checksum to the bitwise complement of beer_id (~beer_id), then print both fields.
Hint
checksum should be a plain class property, not rand — you're computing it yourself in post_randomize() after beer_id already has its final randomized value.
Solution
class Beverage;
rand bit [7:0] beer_id;
bit [7:0] checksum;
constraint c_beer_id { beer_id >= 10;
beer_id <= 50; };
function void post_randomize ();
checksum = ~beer_id;
$display ("beer_id = %0d checksum = %0d", beer_id, checksum);
endfunction
endclass
Because post_randomize() runs after the solver has already assigned beer_id, it's the right place to derive fields like checksum that depend on the final randomized value — computing it in pre_randomize() would use the old, pre-randomization value instead.
Summary
In this tutorial, you learned:
- Class objects are never randomized automatically — you always call the built-in
randomize()method, which returns1on success and0on failure pre_randomize()runs immediately before the solver assigns random valuespost_randomize()runs immediately after, but only ifrandomize()succeeded- Overriding either callback is a clean way to customize an object's randomization behavior without touching
randomize()itself - Neither callback needs (or accepts) the
virtualkeyword, even though both behave virtually
Continuing the Randomization Chapter
Continue with disable randomization to turn off rand/randc on individual variables, and randcase to apply the same ideas to randomizing control flow itself.
When the size of a collection is unknown up front, or the data space is sparse, an associative array is a better fit than a fixed-size or dynamic array. Associative arrays don't allocate any storage until you actually use an index, and that index isn't restricted to integers — it can be of any type.
An associative array works like a look-up table: the type used as the index becomes the lookup key, and that key type also determines the ordering used when you iterate the array.
9 min read | Intermediate Level
What You'll Learn
- How to declare an associative array with any key type, not just integers
- The built-in methods for checking, counting, and deleting entries
- How
first(),last(),next(), andprev()traverse the array in sorted key order - How to nest associative arrays with dynamic arrays in either direction
Syntax
// Value Array_Name [ key ];
data_type array_identifier [ index_type ];
data_type– the type of value stored at each keyarray_identifier– the variable nameindex_type– the key's data type; commonlyintorstring, but any type is allowed
An associative array is recognized by a data type sitting inside the square brackets, e.g. int m_data [string];. Compare that to a dynamic array's empty [ ] or a queue's [$] — all three are unpacked arrays, but each is written differently.
Initialization Example
module tb;
int array1 [int]; // An integer array with integer index
int array2 [string]; // An integer array with string index
string array3 [string]; // A string array with string index
initial begin
// Initialize each dynamic array with some values
array1 = '{ 1 : 22,
6 : 34 };
array2 = '{ "Ross" : 100,
"Joey" : 60 };
array3 = '{ "Apples" : "Oranges",
"Pears" : "44" };
// Print each array
$display ("array1 = %p", array1);
$display ("array2 = %p", array2);
$display ("array3 = %p", array3);
end
endmodule
Output
ncsim> run
array1 = '{1:22, 6:34}
array2 = '{"Joey":60, "Ross":100}
array3 = '{"Apples":"Oranges", "Pears":"44"}
ncsim: *W,RNQUIE: Simulation is complete.
Notice that array2 prints "Joey" before "Ross" even though "Ross" was assigned first in the source — string keys are displayed in alphabetical order, not insertion order. array1's integer keys likewise print numerically ascending (1 before 6), regardless of assignment order.
Quick Check
Q: If you assign array1[6] before array1[1], does $display("%p", array1) print 6 first?
Show Answer
No. Associative arrays with integer keys always print in ascending numeric order regardless of the order the entries were assigned in.
Associative Array Methods
| Method | Description |
|---|---|
function int num (); | Returns the number of entries in the associative array |
function int size (); | Also returns the number of entries; 0 if empty |
function void delete ( [input index] ); | index, when specified, deletes the entry at that index; otherwise the whole array is deleted |
function int exists (input index); | Checks whether an element exists at the specified index; returns 1 if it does, else 0 |
function int first (ref index); | Assigns the value of the first index to the given variable; returns 0 for an empty array |
function int last (ref index); | Assigns the value of the last index to the given variable; returns 0 for an empty array |
function int next (ref index); | Finds the smallest index whose value is greater than the given index |
function int prev (ref index); | Finds the largest index whose value is smaller than the given index |
Associative arrays can have non-consecutive or arbitrary index values, and next()/prev() always walk through them in sorted key order.
module tb;
int aa_array [int];
initial begin
int idx;
// Initialized indices in a mixed order, not 1,2,5,8
aa_array[5] = 20;
aa_array[8] = 10;
aa_array[1] = 50;
aa_array[2] = 100;
// Finds the smallest index whose value is greater than the given index
// Current index is 0, the next smallest value out of 1,2,5,8 is 1
aa_array.next(idx);
$display("aa_array[%0d]=%0d", idx, aa_array[idx]);
// Current index is 1, the next smallest value out of 2,5,8 is 2
aa_array.next(idx);
$display("aa_array[%0d]=%0d", idx, aa_array[idx]);
// Finds the largest index whose value is smaller than the given index
// Current index is 5, the next largest value out of 1,2 is 2
idx = 5;
aa_array.prev(idx);
$display("aa_array[%0d]=%0d", idx, aa_array[idx]);
end
endmodule
Output
xcelium> run aa_array[1]=50 aa_array[2]=100 aa_array[2]=100 xmsim: *W,RNQUIE: Simulation is complete.
idx starts at its default value of 0, and each call to next() updates idx in place, so the second call continues from wherever the first one left off. That's why the two next() calls step 0→1 and then 1→2, walking the sorted keys one at a time.
This sorted-order guarantee is exactly why associative arrays are convenient for building a sorted report from sparse data — iterating with first()/next() visits every populated address, ID, or name in order, without you having to sort anything yourself.
Associative Array Methods Example
module tb;
int fruits_l0 [string];
initial begin
fruits_l0 = '{ "apple" : 4,
"orange" : 10,
"plum" : 9,
"guava" : 1 };
// size() : Print the number of items in the given associative array
$display ("fruits_l0.size() = %0d", fruits_l0.size());
// num() : Another function to print number of items in given array
$display ("fruits_l0.num() = %0d", fruits_l0.num());
// exists() : Check if a particular key exists in this dynamic array
if (fruits_l0.exists ("orange"))
$display ("Found %0d orange !", fruits_l0["orange"]);
if (!fruits_l0.exists ("apricots"))
$display ("Sorry, season for apricots is over ...");
// Note: String indices are taken in alphabetical order
// Correct order: apple, guava, orange, plum
// first() : Get the first element in the array
begin
string f;
// This function returns true if it succeeded and first key is stored
// in the provided string "f"
if (fruits_l0.first (f))
$display ("fruits_l0.first [%s] = %0d", f, fruits_l0[f]);
end
// last() : Get the last element in the array
begin
string f;
if (fruits_l0.last (f))
$display ("fruits_l0.last [%s] = %0d", f, fruits_l0[f]);
end
// prev() : Get the previous element in the array
begin
string f = "orange";
if (fruits_l0.prev (f))
$display ("fruits_l0.prev [%s] = %0d", f, fruits_l0[f]);
end
// next() : Get the next item in the array
begin
string f = "orange";
if (fruits_l0.next (f))
$display ("fruits_l0.next [%s] = %0d", f, fruits_l0[f]);
end
end
endmodule
Output
ncsim> run fruits_l0.size() = 4 fruits_l0.num() = 4 Found 10 orange ! Sorry, season for apricots is over ... fruits_l0.first [apple] = 4 fruits_l0.last [plum] = 9 fruits_l0.prev [guava] = 1 fruits_l0.next [plum] = 9 ncsim: *W,RNQUIE: Simulation is complete.
With keys apple, guava, orange, plum in alphabetical order, prev("orange") lands on guava (the key right before it alphabetically) and next("orange") lands on plum (the key right after it) — each begin...end block resets f to "orange" independently, so the two calls don't interfere with each other.
Quick Check
Q: first() and last() both return an int. What does that return value mean?
Show Answer
Whether the call succeeded. It returns 0 if the array is empty (so there's no first/last element to find) and a non-zero value otherwise — which is why the example wraps each call in an if statement before using the result.
Dynamic Array of Associative Arrays
You can nest these unpacked array types inside one another. Here, each index of a dynamic array holds its own associative array.
module tb;
// Create an associative array with key of type string and value of type int
// for each index in a dynamic array
int fruits [] [string];
initial begin
// Create a dynamic array with size 2
fruits = new [2];
// Initialize the associative array inside each dynamic array index
fruits [0] = '{ "apple" : 1, "grape" : 2 };
fruits [1] = '{ "melon" : 3, "cherry" : 4 };
// Iterate through each index of dynamic array
foreach (fruits[i])
// Iterate through each key of the current index in dynamic array
foreach (fruits[i][fruit])
$display ("fruits[%0d][%s] = %0d", i, fruit, fruits[i][fruit]);
end
endmodule
Output
ncsim> run fruits[0][apple] = 1 fruits[0][grape] = 2 fruits[1][cherry] = 4 fruits[1][melon] = 3 ncsim: *W,RNQUIE: Simulation is complete.
The outer foreach walks the dynamic array's numeric indices in order (0, then 1), while each inner foreach walks that entry's string keys alphabetically — which is why cherry prints before melon even though melon was assigned first.
Dynamic Array Within Each Index of an Associative Array
The nesting also works the other way around: an associative array whose values are dynamic arrays.
// Create a new typedef that represents a dynamic array
typedef int int_da [];
module tb;
// Create an associative array where key is a string
// and value is a dynamic array
int_da fruits [string];
initial begin
// For key "apple", create a dynamic array that can hold 2 items
fruits ["apple"] = new [2];
// Initialize the dynamic array with some values
fruits ["apple"] = '{ 4, 5};
// Iterate through each key, where key represented by str1
foreach (fruits[str1])
// Iterate through each item inside the current dynamic array ie.fruits[str1]
foreach (fruits[str1][i])
$display ("fruits[%s][%0d] = %0d", str1, i, fruits[str1][i]);
end
endmodule
Output
ncsim> run fruits[apple][0] = 4 fruits[apple][1] = 5 ncsim: *W,RNQUIE: Simulation is complete.
The typedef int int_da []; line is what makes this declaration possible — a dynamic array's dimension has to be given a name via typedef before it can be used as the value type of another array.
An associative array of dynamic arrays is a natural model for something like per-address memory content in a sparse memory model, where each populated address holds a variable-length burst of data.
Common Mistakes
Mistake #1: Assuming iteration follows insertion order
As shown throughout this article, foreach, first()/next(), and direct %p printing all visit associative array entries in sorted key order — numeric ascending for integer keys, alphabetical for string keys — never in the order the entries were assigned.
Mistake #2: Indexing a key that doesn't exist without checking first
Reading fruits_l0["kiwi"] when "kiwi" was never assigned returns the type's default value and issues a warning — but a plain read does not add a new entry to the array; only a write (or passing the key by reference) actually allocates one. Use exists() first if you need to distinguish "not present" from "present with a default value," and don't assume a read alone grows the array.
Mistake #3: Forgetting that first()/last()/next()/prev() return success, not the key
The key or index is written into the ref argument, not the return value. if (fruits_l0.first(f)) checks whether the call succeeded; f itself holds the actual first key afterward.
Mistake #4: Using an associative array where a queue would fit better
If you need strict insertion order preserved, or need to push/pop from either end, an associative array is the wrong tool even though it can technically store the same data — reach for a queue instead.
Practice Exercise
Challenge: Build a Register Name Lookup
Declare an associative array named reg_addr that maps register names (strings) to their addresses (int). Add entries for "CTRL" (0x10), "STATUS" (0x14), and "DATA" (0x18). Check whether "CTRL" exists before printing its address, then print every entry using first()/next().
Hint
Use string as the key type: int reg_addr [string];. Remember that first()/next() return 0 when there's nothing left to visit, which makes them a natural fit for a while loop.
Solution
module tb;
int reg_addr [string];
initial begin
reg_addr["CTRL"] = 'h10;
reg_addr["STATUS"] = 'h14;
reg_addr["DATA"] = 'h18;
if (reg_addr.exists("CTRL"))
$display("CTRL is at 0x%0h", reg_addr["CTRL"]);
begin
string name;
if (reg_addr.first(name)) begin
$display("%s = 0x%0h", name, reg_addr[name]);
while (reg_addr.next(name))
$display("%s = 0x%0h", name, reg_addr[name]);
end
end
end
endmodule
Summary
In this tutorial, you learned:
- An associative array is recognized by a data type inside the square brackets, and allocates no storage until an index is actually used
size()/num()count entries,exists()checks for a key, anddelete()removes one entry or the whole arrayfirst(),last(),next(), andprev()traverse the array in sorted key order — numeric ascending for integer keys, alphabetical for string keys — not insertion orderfirst()/last()/next()/prev()return success/failure; the actual key comes back through therefargument- Associative arrays can nest with dynamic arrays in either direction, useful for sparse, variable-length data
A dynamic array is an unpacked array whose size can be set or changed at runtime, unlike a static array where the size is fixed at declaration. A dynamic array's default size is zero until it's explicitly set by the new[] constructor.
7 min read | Intermediate Level
What You'll Learn
- How to declare and size a dynamic array with
new[] - The built-in
size()anddelete()methods - How to grow a dynamic array while keeping its existing contents
- Why copying a dynamic array to another variable doesn't create a shared reference
Syntax
A dynamic array's dimension is specified with empty square brackets [ ].
[data_type] [identifier_name] [];
bit [7:0] stack []; // A dynamic array of 8-bit vector
string names []; // A dynamic array that can contain strings
The new[] function allocates a size for the array and can initialize its elements at the same time.
An empty [ ] is what distinguishes a dynamic array from a static one at a glance — there's no size or range inside the brackets, since the size isn't known until new[] runs.
Dynamic Array Example
module tb;
// Create a dynamic array that can hold elements of type int
int array [];
initial begin
// Create a size for the dynamic array -> size here is 5
// so that it can hold 5 values
array = new [5];
// Initialize the array with five values
array = '{31, 67, 10, 4, 99};
// Loop through the array and print their values
foreach (array[i])
$display ("array[%0d] = %0d", i, array[i]);
end
endmodule
Output
ncsim> run array[0] = 31 array[1] = 67 array[2] = 10 array[3] = 4 array[4] = 99 ncsim: *W,RNQUIE: Simulation is complete.
array = new [5]; allocates 5 elements, each initialized to the type's default value (0 for int). The next line then overwrites all 5 slots with the given values — sizing and initializing are two separate steps here, though new[] can also take an initializer directly, as shown further down.
Quick Check
Q: What is array.size() immediately after int array []; is declared, before any new[] call?
Show Answer
0. A dynamic array has no elements until it's explicitly sized with new[]; declaring it alone only creates the handle, not the storage.
Dynamic Array Methods
| Method | Description |
|---|---|
function int size (); | Returns the current size of the array, 0 if the array has not been created |
function void delete (); | Empties the array, resulting in a zero-sized array |
module tb;
// Create a dynamic array that can hold elements of type string
string fruits [];
initial begin
// Create a size for the dynamic array -> size here is 3
// so that it can hold 3 values
fruits = new [3];
// Initialize the array with three values
fruits = '{"apple", "orange", "mango"};
// Print size of the dynamic array
$display ("fruits.size() = %0d", fruits.size());
// Empty the dynamic array by deleting all items
fruits.delete();
$display ("fruits.size() = %0d", fruits.size());
end
endmodule
Output
ncsim> run fruits.size() = 3 fruits.size() = 0 ncsim: *W,RNQUIE: Simulation is complete.
delete() on a dynamic array is different from delete() on a queue — a dynamic array's delete() takes no arguments and always clears the whole array, while a queue's version can optionally target a single index.
How to Add New Items to a Dynamic Array?
Since new[] allocates a fresh block of storage, adding elements to an existing dynamic array without losing its current contents means copying the old contents into the newly sized array as part of the same call.
int array [];
array = new [10];
// This creates one more slot in the array, while keeping old contents
array = new [array.size() + 1] (array);
Passing (array) as the second argument to new[] tells it to copy the existing elements into the newly allocated storage before the assignment completes. Without that argument, new [array.size() + 1] would still resize the array, but every element would come back at its default value.
Quick Check
Q: What would array = new [array.size() + 1]; (without the trailing (array)) do to the existing elements?
Show Answer
It would discard them. Without passing the old array as the copy argument, new[] allocates a fresh block where every element starts at its default value — the previous contents are lost, even though the size still grows by one.
Copying Dynamic Array Example
module tb;
// Create two dynamic arrays of type int
int array [];
int id [];
initial begin
// Allocate 5 memory locations to "array" and initialize with values
array = new [5];
array = '{1, 2, 3, 4, 5};
// Copy "array" to "id"
id = array;
// Display contents of "id"
$display ("id = %p", id);
// Grow size by 1 and copy existing elements to the new dyn.Array "id"
id = new [id.size() + 1] (id);
// Assign value 6 to the newly added location [index 5]
id [id.size() - 1] = 6;
// Display contents of new "id"
$display ("New id = %p", id);
// Display size of both arrays
$display ("array.size() = %0d, id.size() = %0d", array.size(), id.size());
end
endmodule
Output
run -all;
ncsim> run
id = '{1, 2, 3, 4, 5}
New id = '{1, 2, 3, 4, 5, 6}
array.size() = 5, id.size() = 6
ncsim: *W,RNQUIE: Simulation is complete.
id = array; copies every element into id's own separate storage, which is exactly why array is still size 5 at the end while id has grown to size 6: the two variables never shared any memory to begin with.
This copy-then-grow pattern is common in testbenches for building up a results array one entry at a time when the final count isn't known in advance — though a queue with push_back() is usually a simpler choice for that exact job.
Common Mistakes
Mistake #1: Assuming new[] is required before every assignment
Actually, assigning an array literal or another array directly to an unsized dynamic array — array = '{1, 2, 3}; — works fine without calling new[] first: per IEEE 1800-2012 §7.6, assigning an array (or array literal) to a dynamic array automatically resizes it to match. new[] is only required when you want to pre-allocate a specific size before assigning values, or when growing an existing array while preserving its contents (the pattern shown above).
Mistake #2: Forgetting the copy argument when resizing
array = new [array.size() + 1]; grows the array but resets every element to its default value, since no old array was passed in to copy from. Use array = new [array.size() + 1] (array); to keep the existing contents.
Mistake #3: Assuming array-to-array assignment shares storage
id = array; performs an element-wise copy, not an alias. Changing id afterward, including resizing it, has no effect on array — unlike assigning one class handle to another, which does share the same underlying object.
Mistake #4: Calling delete() expecting a single-index removal
A dynamic array's delete() takes no index and clears the entire array. If you need to remove just one element while keeping the rest, a dynamic array isn't the right tool — use a queue and its indexed delete() instead.
Practice Exercise
Challenge: Grow an Array of Scores
Declare a dynamic array of int named scores, size it to hold 3 values (10, 20, 30), then grow it by one element while keeping the existing values, and set the new last element to 40. Print the final array and its size.
Hint
Use new [scores.size() + 1] (scores) to grow while preserving contents, then assign the new element using scores[scores.size() - 1].
Solution
module tb;
int scores [];
initial begin
scores = new [3];
scores = '{10, 20, 30};
scores = new [scores.size() + 1] (scores);
scores [scores.size() - 1] = 40;
$display ("scores = %p, size = %0d", scores, scores.size());
end
endmodule
Summary
In this tutorial, you learned:
- A dynamic array is an unpacked array declared with empty
[ ], with a default size of 0 until sized bynew[] size()returns the current element count, anddelete()clears the entire array (no index argument)- Growing a dynamic array while preserving its contents requires passing the old array into
new[], likenew [size+1] (old_array) - Assigning one dynamic array to another copies the elements — it does not create a shared reference, so resizing one never affects the other
A SystemVerilog queue is a First-In-First-Out data structure with a variable size, holding elements of the same data type. It behaves like a one-dimensional unpacked array that grows and shrinks automatically, and supports indexing, concatenation, and slicing operators. Queues can also be passed to tasks and functions as ref or non-ref arguments.
9 min read | Intermediate Level
What You'll Learn
- The difference between bounded and unbounded queues
- How to declare, index, and slice a queue
- The built-in queue methods for inserting, deleting, and popping elements
- How to build a queue of class objects or a queue of dynamic arrays
Types of Queues
A queue is recognized by the $ operator used in its size specification.
A bounded queue has a fixed maximum size and can hold a limited number of entries. The queue below has depth N and is already full — it cannot accept more items.
[data_type] [name_of_queue] [$:N];
int bounded_queue [$:10]; // Max size 11 (last valid index is 10)
An unbounded queue can grow to hold an unlimited number of entries. The queue below currently has 5 items but can keep accepting more.
[data_type] [name_of_queue] [$];
int unbounded_queue [$]; // Unlimited entries
Syntax
Queues support both array-style operators and dedicated methods for the same jobs — the operators below work directly on queue indices and slices, without calling a method.
string name_list [$]; // A queue of string elements
bit [3:0] data [$]; // A queue of 4-bit elements
logic [7:0] elements [$:127]; // A bounded queue of 8-bits with maximum size of 128 slots
int q1 [$] = '{ 1, 2, 3, 4, 5 }; // Integer queue, initialize elements
int q2 [$]; // Integer queue, empty
int tmp; // Temporary variable to store values
tmp = q1 [0]; // Get first item of q1 (index 0) and store in tmp
tmp = q1 [$]; // Get last item of q1 (index 4) and store in tmp
q2 = q1; // Copy all elements in q1 into q2
q1 = {}; // Empty the queue (delete all items)
q2[2] = 15; // Replace element at index 2 with 15
q2.insert (2, 15); // Inserts value 15 to index# 2
q2 = { q2, 22 }; // Append 22 to q2
q2 = { 99, q2 }; // Put 99 as the first element of q2
q2 = q2 [1:$]; // Delete first item
q2 = q2 [0:$-1]; // Delete last item
q2 = q2 [1:$-1]; // Delete first and last item
The $ symbol always means "the last index" when used inside brackets, so q1[$] reads as "the element at the last index of q1," and q2[1:$] reads as "everything from index 1 through the last index."
SystemVerilog Queue Example
module tb;
// Create a queue that can store "string" values
string fruits[$] = '{"orange", "apple", "kiwi"};
initial begin
// Iterate and access each queue element
foreach (fruits[i])
$display ("fruits[%0d] = %s", i, fruits[i]);
// Display elements in a queue
$display ("fruits = %p", fruits);
// Delete all elements in the queue
fruits = {};
$display ("After deletion, fruits = %p", fruits);
end
endmodule
Output
ncsim> run
fruits[0] = orange
fruits[1] = apple
fruits[2] = kiwi
fruits = '{"orange", "apple", "kiwi"}
After deletion, fruits = '{}
ncsim: *W,RNQUIE: Simulation is complete.
Quick Check
Q: After fruits = {};, what does fruits.size() return?
Show Answer
0. Assigning an empty concatenation {} to a queue removes every element, and a queue with no elements has a size of 0.
What Are Queue Slice Expressions?
A slice expression selects a subset of an existing queue using the [start:end] syntax, where either side can be a literal index or $ for the last index.
Some simulators produce different results for edge-case slice expressions, so using the dedicated queue methods covered further down is generally recommended over relying on slicing for insert/delete logic.
module tb;
// Create a queue that can store "string" values
string fruits[$] = '{ "orange", "apple", "lemon", "kiwi" };
initial begin
// Select a subset of the queue
$display ("citrus fruits = %p", fruits[1:2]);
// Get elements from index 1 to end of queue
$display ("fruits = %p", fruits[1:$]);
// Add element to the end of queue
fruits[$+1] = "pineapple";
$display ("fruits = %p", fruits);
// Delete first element
fruits = fruits[1:$];
$display ("Remove orange, fruits = %p", fruits);
end
endmodule
Output
Compiler version J-2014.12-SP1-1; Runtime version J-2014.12-SP1-1; May 15 16:21 2018
citrus fruits = '{"apple", "lemon"}
fruits = '{"apple", "lemon", "kiwi"}
fruits = '{"orange", "apple", "lemon", "kiwi", "pineapple"}
Remove orange, fruits = '{"apple", "lemon", "kiwi", "pineapple"}
V C S S i m u l a t i o n R e p o r t
Writing to fruits[$+1] is a common idiom for appending — since $ is the last valid index, $+1 is exactly one past the end, which extends the queue rather than going out of bounds.
Queue slicing is handy for scoreboard cleanup — for example, pending_txns = pending_txns[1:$]; to discard a transaction once it's been checked and move on to the next one.
SystemVerilog Queue Methods
In addition to the array operators above, queues expose dedicated methods for the same operations, which read more clearly in testbench code.
| Method | Description |
|---|---|
function int size (); | Returns the number of items in the queue, 0 if empty |
function void insert (input integer index, input element_t item); | Inserts the given item at the specified index position |
function void delete ( [input integer index] ); | Deletes the element at the specified index; if not provided, all elements are deleted |
function element_t pop_front (); | Removes and returns the first element of the queue |
function element_t pop_back (); | Removes and returns the last element of the queue |
function void push_front (input element_t item); | Inserts the given element at the front of the queue |
function void push_back (input element_t item); | Inserts the given element at the end of the queue |
SystemVerilog Queue Methods Example
module tb;
string fruits[$] = '{"apple", "pear", "mango", "banana"};
initial begin
// size() - Gets size of the given queue
$display ("Number of fruits=%0d fruits=%p", fruits.size(), fruits);
// insert() - Insert an element to the given index
fruits.insert (1, "peach");
$display ("Insert peach, size=%0d fruits=%p", fruits.size(), fruits);
// delete() - Delete element at given index
fruits.delete (3);
$display ("Delete mango, size=%0d fruits=%p", fruits.size(), fruits);
// pop_front() - Pop out element at the front
$display ("Pop %s, size=%0d fruits=%p", fruits.pop_front(), fruits.size(), fruits);
// push_front() - Push a new element to front of the queue
fruits.push_front("apricot");
$display ("Push apricot, size=%0d fruits=%p", fruits.size(), fruits);
// pop_back() - Pop out element from the back
$display ("Pop %s, size=%0d fruits=%p", fruits.pop_back(), fruits.size(), fruits);
// push_back() - Push element to the back
fruits.push_back("plum");
$display ("Push plum, size=%0d fruits=%p", fruits.size(), fruits);
end
endmodule
Output
ncsim> run
Number of fruits=4 fruits='{"apple", "pear", "mango", "banana"}
Insert peach, size=5 fruits='{"apple", "peach", "pear", "mango", "banana"}
Delete mango, size=4 fruits='{"apple", "peach", "pear", "banana"}
Pop apple, size=3 fruits='{"peach", "pear", "banana"}
Push apricot, size=4 fruits='{"apricot", "peach", "pear", "banana"}
Pop banana, size=3 fruits='{"apricot", "peach", "pear"}
Push plum, size=4 fruits='{"apricot", "peach", "pear", "plum"}
ncsim: *W,RNQUIE: Simulation is complete.
Notice that fruits.delete(3) deletes by current index, not original index — after the earlier insert, "mango" had shifted from index 2 to index 3, which is why delete(3) is the call that removes it.
This exact pattern — push_back() for arriving transactions and pop_front() for processing them in order — is the standard way to model an in-order scoreboard or a FIFO-style pipeline stage in a testbench.
Quick Check
Q: Which method would you use to remove and return the oldest item pushed into a FIFO-style queue?
Show Answer
pop_front(). If items are always added with push_back(), the oldest item is always at the front, so pop_front() retrieves items in the same order they were pushed — true FIFO behavior.
How to Create a Queue of Classes in SystemVerilog?
A queue can hold class handles just as easily as it holds simple types like int or string.
// Define a class with a single string member called "name"
class Fruit;
string name;
function new (string name="Unknown");
this.name = name;
endfunction
endclass
module tb;
// Create a queue that can hold values of data type "Fruit"
Fruit list [$];
initial begin
// Create a new class object and call it "Apple"
// and push into the queue
Fruit f = new ("Apple");
list.push_back (f);
// Create another class object and call it "Banana" and
// push into the queue
f = new ("Banana");
list.push_back (f);
// Iterate through queue and access each class object
foreach (list[i])
$display ("list[%0d] = %s", i, list[i].name);
// Simply print the whole queue, note that class handles are printed
// and not class object contents
$display ("list = %p", list);
end
endmodule
Output
ncsim> run
list[0] = Apple
list[1] = Banana
list = '{$unit_0x4ccdf83b::Fruit@2_1, $unit_0x4ccdf83b::Fruit@4_1}
ncsim: *W,RNQUIE: Simulation is complete.
Printing list directly with %p shows each element's class handle (an internal reference), not its field values — if you want to see name, you need to access it explicitly, as the foreach loop does above.
A queue of class handles is exactly how most UVM-style scoreboards store outstanding transactions — each entry is a handle to a transaction object, not a copy of raw data.
How to Create a Queue of Dynamic Arrays in SystemVerilog?
A queue's element type can itself be a dynamic array, giving you a queue whose entries are variable-length lists.
// Declare a dynamic array to store strings as a datatype
typedef string str_da [];
module tb;
// This is a queue of dynamic arrays
str_da list [$];
initial begin
// Initialize separate dynamic arrays with some values
str_da marvel = '{"Spiderman", "Hulk", "Captain America", "Iron Man"};
str_da dcWorld = '{"Batman", "Superman" };
// Push the previously created dynamic arrays to queue
list.push_back (marvel);
list.push_back (dcWorld);
// Iterate through the queue and access dynamic array elements
foreach (list[i])
foreach (list[i][j])
$display ("list[%0d][%0d] = %s", i, j, list[i][j]);
// Simply print the queue
$display ("list = %p", list);
end
endmodule
Output
ncsim> run
list[0][0] = Spiderman
list[0][1] = Hulk
list[0][2] = Captain America
list[0][3] = Iron Man
list[1][0] = Batman
list[1][1] = Superman
list = '{'{"Spiderman", "Hulk", "Captain America", "Iron Man"}, '{"Batman", "Superman"}}
ncsim: *W,RNQUIE: Simulation is complete.
The outer foreach (list[i]) walks each dynamic array in the queue, and the inner foreach (list[i][j]) walks the elements within that array — the same nested pattern used for any multidimensional unpacked structure.
Common Mistakes
Mistake #1: Popping from an empty queue
Calling pop_front() or pop_back() on a queue with no elements is a runtime warning in most simulators and can silently fail. Check queue.size() first if you're not certain an item is waiting.
Mistake #2: Deleting by the wrong index after a prior insert/delete
Every insert() or delete() shifts the indices of the elements after it. As shown in the methods example, delete(3) only removed "mango" because a prior insert() had already shifted it from index 2 to index 3 - always index against the queue's current state, not its original layout.
Mistake #3: Assuming a bounded queue silently drops excess pushes
Pushing beyond a bounded queue's declared depth ([$:N]) doesn't raise an error - any element that ends up beyond the bound is simply discarded, with only a warning issued. Check size() against the bound before pushing if silently losing an overflow element would be a real problem for your testbench.
Mistake #4: Expecting %p on a class queue to print field values
$display("%p", list) on a queue of class handles prints the handle representation, not the object's fields. Loop through the queue and call each object's own print method (or access its fields directly) if you need to see the actual data.
Practice Exercise
Challenge: Build a Simple FIFO Scoreboard
Declare an unbounded queue of int named expected_q. Push the values 10, 20, and 30 onto it using push_back(), then pop and print each value in order using pop_front() until the queue is empty.
Hint
Use a while (expected_q.size() > 0) loop so you don't call pop_front() on an empty queue.
Solution
module tb;
int expected_q [$];
initial begin
expected_q.push_back(10);
expected_q.push_back(20);
expected_q.push_back(30);
while (expected_q.size() > 0) begin
$display("Popped %0d, remaining size=%0d", expected_q.pop_front(), expected_q.size());
end
end
endmodule
Summary
In this tutorial, you learned:
- A queue is a variable-size, FIFO-ordered data structure recognized by the
$operator, and comes in bounded ([$:N]) and unbounded ([$]) forms - Queues support both array-style indexing/slicing and dedicated methods for the same operations
push_front()/push_back()add elements;pop_front()/pop_back()remove and return them;insert()/delete()work by index- Deleting or inserting by index shifts everything after it, so always index against the queue's current state
- A queue can hold class handles or dynamic arrays as its element type, not just simple data types
Quiz
No quiz questions available for this article.