This article introduces the building blocks of the Randomization chapter: what randomization is and why it matters, the two ways to trigger it depending on where your variable lives, why checking its return value matters, and how a basic constraint lets you target stimulus toward specific scenarios.
6 min read | Intermediate Level
What You'll Learn
- Why constrained-random verification exists and what problem it solves
- The two ways to trigger randomization:
rand/randcclass properties andstd::randomize()for plain variables - Why checking the return value of
randomize()matters - How a basic constraint targets random stimulus toward specific scenarios
What Is Randomization and Why Does It Help?
Directed tests take a long time to develop because you have to think through every scenario you want to check, and there's a high chance you'll miss some corner case. Randomization flips this around: rather than hand-picking every value, you let SystemVerilog's constraint solver pick legal values that fall within a valid range and apply them to the signals you're interested in, run after run.
A single randomized run only exercises one legal combination out of many. Run the same randomized test dozens or hundreds of times, though, and the solver's picks spread across the entire legal space — including combinations you would never have thought to write a directed test for.
Where Is Constrained-Random Verification Used?
CRV is standard practice for verifying protocol interfaces, memory controllers, and bus arbiters, where the number of legal input combinations is far too large to enumerate by hand. Randomized address, data, and control fields combined with functional coverage are how modern testbenches gain confidence that a design has been exercised thoroughly.
Two Ways to Randomize
SystemVerilog gives you two ways to trigger randomization, depending on where the variable you want to randomize lives: mark a class property with rand or randc and call the object's built-in randomize() method, or call std::randomize() directly on a variable that isn't part of a class at all.
Randomizing Class Properties
Randomization is enabled per-variable by adding the rand or randc qualifier to a class member. SystemVerilog Random covers the difference between the two in depth, along with how they apply to arrays, queues, and dynamic arrays — for now, just know that both keywords make a property randomizable when you call randomize().
rand <type> <variable_name>; // random, any legal value each call
randc <type> <variable_name>; // random-cyclic, no repeats until the full set is exhausted
Parameters:
rand— marks the variable for standard randomization (required keyword)randc— marks the variable for cyclic randomization (required keyword)<type>— any legal data type such asbit,int, or an enum
Here's the simplest possible use of rand — no constraint block at all yet, just a property and a call to randomize():
class myPacket;
rand bit [3:0] mode; // no constraint - any value 0 to 15 is equally likely
endclass
module tb_top;
myPacket pkt;
initial begin
pkt = new();
pkt.randomize();
$display("mode = %0d", pkt.mode);
end
endmodule
Because there's no constraint block, mode can land anywhere from 0 to 15 with equal probability on every call to randomize(). Once you add a constraint block (covered later in this article), you narrow that range down to only the values you actually want.
Randomizing Plain Variables with std::randomize()
Not everything you want to randomize lives inside a class. std::randomize() is a built-in function that randomizes one or more plain variables directly — local variables in a task or function, module-level variables, or anything else that isn't a class property — without requiring the rand/randc qualifier or a surrounding class at all.
module tb_top;
initial begin
int addr, data;
// Randomize plain (non-rand) local variables directly, with an inline constraint
if (std::randomize(addr, data) with { addr inside {[0:255]}; data < 100; }) begin
$display("addr = %0d data = %0d", addr, data);
end else begin
$display("randomization failed");
end
end
endmodule
The with { ... } clause works exactly like an inline constraint on a class object — it applies only to that one call. The std:: prefix explicitly calls the global randomize function rather than a class's own randomize() method, which matters once you're calling it from inside a class (see Mistake #3 below).
Where Is std::randomize() Used?
std::randomize() shows up whenever you need one or two random values without the overhead of writing a whole class — randomizing a delay before driving a signal, picking a random burst length for a loop, or generating a quick randomized value directly inside a testbench.
Always Check the Return Value
Either way you randomize, randomize() and std::randomize() both return 1 on success and 0 if the constraints can't be satisfied — and on failure, the variables simply keep their previous values.
Always check the return value of randomize() (or std::randomize()), typically with assert(). Ignoring a failed call means your test silently continues with stale, non-random data instead of flagging a broken constraint.
"Checking the return value" means wrapping the call in an if (or assert) and reacting when it's 0, instead of calling randomize() as a bare statement. The example below randomizes the same object twice: once normally, and once with an inline constraint that deliberately conflicts with the class-level constraint, so you can see what a caught failure looks like.
class myPacket;
rand bit [1:0] mode;
constraint c_mode { mode < 3; } // mode can only be 0, 1, or 2
endclass
module tb_top;
myPacket pkt;
initial begin
pkt = new();
// Effective pattern: branch on the return value instead of trusting it blindly
if (pkt.randomize()) begin
$display("Randomization OK -> mode = %0d", pkt.mode);
end else begin
$display("Randomization FAIL -> mode unchanged, still = %0d", pkt.mode);
end
// mode == 5 can never satisfy c_mode (mode < 3), so this call is
// guaranteed to fail - a deliberate example of a caught failure
if (pkt.randomize() with { mode == 5; }) begin
$display("Randomization OK -> mode = %0d", pkt.mode);
end else begin
$display("Randomization FAIL -> mode unchanged, still = %0d", pkt.mode);
end
end
endmodule
The first call has no conflict, so it succeeds and pkt.mode gets a fresh random value from {0, 1, 2}. The second call adds an inline constraint (mode == 5) that can never be true alongside c_mode (mode < 3), so randomize() returns 0, the else branch runs, and pkt.mode is left exactly as it was — it is not set to 5. That's the practical meaning of "checking the return value": it's the difference between silently running with unintended data and actively catching the exact constraint that broke.
Quick Check
Q: A class-level constraint says addr < 100. You call randomize() with an inline constraint with { addr > 200; }. What happens?
Show Answer
randomize() returns 0. Inline constraints are combined with all existing constraint blocks using logical AND, and addr < 100 together with addr > 200 has no solution.
What Are Constraints?
A rand or randc property with no constraint block, like the first mode example above, can take on any legal value in its declared range. Most of the time, though, you don't want the entire range — you want to target a specific subset of scenarios: legal opcodes, valid address windows, or corner cases you're specifically trying to hit. A constraint block narrows the random search space down to exactly the values that matter, using one or more relational expressions. The simplest form is a plain comparison:
class myPacket;
rand bit [7:0] mode;
constraint c_mode { mode > 2; } // mode can only be 3 through 255
endclass
Adding c_mode here means every call to randomize() is guaranteed to produce a mode value greater than 2 — the solver simply won't pick anything outside that window. This is the mechanism behind targeted stimulus: instead of hoping a wide random range eventually lands on the scenario you care about, a constraint steers every single randomization attempt toward it.
Beyond simple comparisons like this, SystemVerilog also supports range checks with inside, weighted random distributions with dist, and constraints that reference other variables. Those styles deserve their own space rather than a quick summary here — see SystemVerilog Constraints and the worked Constraint Examples article for the full picture.
rand, randc, and constraint are testbench (verification) constructs, not synthesizable RTL. You'll find them inside classes used to build stimulus and check responses in a testbench, not inside a synthesizable design module.
Common Beginner Mistakes
Mistake #1: Not checking the return value of randomize()
If a constraint conflict makes randomization fail, randomize() returns 0 and the variables simply keep their old values — no error, no random data. Why? Ignoring the return value means the test keeps running with stale data instead of flagging the real problem, which can hide bugs in your constraints for a long time.
Mistake #2: Writing constraints that quietly contradict each other
If one constraint block says key == 3 and another says key < 2, no legal value exists and randomize() fails at run time. Why? All active constraint blocks on a class are combined with logical AND, so conflicting ranges across separate blocks are just as fatal as conflicting statements in the same block.
Mistake #3: Forgetting the std:: prefix inside a class method
Inside a class method, a bare call to randomize() resolves to that class's own built-in randomize() method, which randomizes the class's own rand/randc properties — not the global function. Why? If you need to randomize local or non-rand variables from inside a class method, prefix the call with std:: so SystemVerilog knows you mean the global randomize(), not the object's own method.
Continuing the Randomization Chapter
From here, the rest of the Randomization chapter builds on these basics: SystemVerilog Random covers rand and randc in depth, pre_randomize and post_randomize let you set up state before and after a call, disable randomization covers turning off rand/randc on individual variables, and randcase applies the same ideas to randomizing control flow itself.
Practice Exercise
Challenge: Randomize a Delay with std::randomize()
Without writing a class, use std::randomize() to randomize a local variable delay (an int) so it's constrained between 5 and 20, inclusive. Check the return value and print an error if it fails.
Hint
You don't need a class or the rand keyword at all — declare delay as a plain int and pass it directly to std::randomize() with an inline with constraint.
Solution
module tb_top;
initial begin
int delay;
if (std::randomize(delay) with { delay inside {[5:20]}; }) begin
$display("delay = %0d", delay);
end else begin
$display("ERROR: randomization of delay failed");
end
end
endmodule
delay never needed a rand qualifier or a surrounding class — std::randomize() randomizes the plain local variable directly, and the with clause supplies the range as an inline constraint.
Summary
In this tutorial, you learned:
- Constrained Random Verification generates legal stimulus automatically instead of relying on hand-written directed tests
- Class properties become randomizable with the
randorrandcqualifier — the difference between them is covered in the next article std::randomize()randomizes plain variables directly, without needing a class or therand/randcqualifiers- Always check the return value of
randomize()to catch conflicting constraints - A
constraintblock narrows the random search space to legal, targeted values — ranges,inside, anddistare covered in the Constraints chapter rand/randc/constraintare verification-only constructs, not synthesizable RTL
A class is the foundation of Object-Oriented Programming (OOP) in SystemVerilog. Instead of scattering related signals and the functions that act on them across your testbench, a class lets you group them into a single, reusable unit. This article walks through class basics — declaring a class, building a constructor, and creating objects — using a simple packet example you'll recognize from real verification environments.
8 min read | Intermediate Level
What You'll Learn
- What a SystemVerilog class is and why testbenches are built around it
- How to declare a class, create objects, and access their properties/methods
- How to build arrays of class objects
What Is a Class?
class is a user-defined data type — an OOP construct — used to encapsulate properties (data) and methods (tasks/functions) that operate on that data. Think of a class as a blueprint: it describes what an object looks like and what it can do, but it isn't usable on its own until you create an actual object from it.
As the diagram shows, myPacket is the blueprint. Every time you call new(), SystemVerilog allocates a fresh, independent object — pkt0 and pkt1 each get their own copy of header, encode, mode, data, and stop. The method display(), however, is defined once and shared by every object.
Syntax
class class_name;
// property declarations
// method declarations (functions/tasks)
endclass
Parameters:
class_name— identifier for the class (required)- Properties — variables declared inside the class body, accessible via the dot operator on an object handle
- Methods —
functionortaskdeclarations that operate on the class's own properties
Variations:
A class with a constructor that has default argument values:
class myClass;
int data;
function new(int data = 0);
this.data = data;
endfunction
endclass
Here's a complete class example:
class myPacket;
bit [2:0] header;
bit encode;
bit [2:0] mode;
bit [7:0] data;
bit stop;
function new (bit [2:0] header = 3'h1, bit [2:0] mode = 5);
this.header = header;
this.encode = 0;
this.mode = mode;
this.stop = 1;
endfunction
function void display ();
$display ("Header = 0x%0h, Encode = %0b, Mode = 0x%0h, Stop = %0b",
this.header, this.encode, this.mode, this.stop);
endfunction
endclass
A few key things to note in the example above:
function new()is called the constructor and is automatically called upon object creation- this keyword is used to refer to the current object's own properties/methods — it distinguishes the class property header from the constructor argument of the same name
display()is a function, and rightly so, because displaying values does not consume simulation time. Tasks are reserved for code that needs to model a delay or wait on an eventfunction new()has default values for its arguments, so callingnew()with no arguments creates a packet with header = 3'h1, mode = 3'h5, and the rest set by the body of the constructor
A class declaration by itself does not create any storage or consume any memory. Memory is only allocated when you call new() to construct an object.
Where Are Classes Used?
Almost every reusable testbench component — transactions, drivers, monitors, scoreboards — is written as a SystemVerilog class. The UVM library itself is essentially a large set of base classes (uvm_component, uvm_sequence_item, and so on) that verification engineers extend to build their own environments.
How Do I Access Properties and Methods?
To use a class, you create an object of it, which acts as a handle to its properties and methods. Object handles are declared just like any other variable, but they don't point to real storage until new() is called.
module tb_top;
myPacket pkt0, pkt1;
initial begin
pkt0 = new (3'h2, 3'h3);
pkt0.display ();
pkt1 = new ();
pkt1.display ();
end
endmodule
Output
Header = 0x2, Encode = 0, Mode = 0x3, Stop = 1 Header = 0x1, Encode = 0, Mode = 0x5, Stop = 1
Notice that pkt0 and pkt1 hold completely independent data. Changing pkt0.header later has no effect on pkt1.header — each call to new() creates a distinct copy of the class's properties.
Quick Check
Q: If you declare myPacket pkt0; but never call pkt0 = new();, what happens when you try pkt0.display();?
Show Answer
pkt0 holds the default value null until it is constructed. Calling a method on a null handle causes a run-time error (commonly reported as a null object access / segmentation fault by the simulator), because there's no actual object in memory to operate on.
How Do I Create an Array of Class Objects?
An array of class objects can be created in a way similar to how you create an array of any other data type, such as int. Each element of the array is its own object handle and must be constructed individually.
module tb_top;
myPacket pkt0 [3];
initial begin
for(int i = 0; i < $size (pkt0); i++) begin
pkt0[i] = new ();
pkt0[i].display ();
end
end
endmodule
Since each myPacket object had no arguments passed to its constructor new(), default values are applied for every element.
Output
Header = 0x1, Encode = 0, Mode = 0x5, Stop = 1 Header = 0x1, Encode = 0, Mode = 0x5, Stop = 1 Header = 0x1, Encode = 0, Mode = 0x5, Stop = 1
Declaring myPacket pkt0 [3]; only reserves three handles — it does not allocate three objects. Forgetting to call new() inside the loop is a common mistake that leaves every handle pointing to null.
Common Beginner Mistakes
Mistake #1: Forgetting to call new()
Wrong: myPacket pkt0; pkt0.display();
Right: myPacket pkt0; pkt0 = new(); pkt0.display();
Why? Declaring a handle only creates a reference variable; it does not build the object. You must explicitly call the constructor before using any property or method.
Mistake #2: Mixing up the order of positional constructor arguments
Wrong: Calling new(3'h3, 3'h2) when you meant header = 3'h2 and mode = 3'h3.
Right: Pass arguments in the same order they're declared in function new(), or check the constructor signature before calling it.
Why? SystemVerilog matches positional arguments by order, not by name. Swapping two arguments of the same type compiles fine but silently assigns the wrong value to each property.
Mistake #3: Confusing constructor arguments with class properties of the same name
Wrong: Writing header = header; inside function new(bit [2:0] header) and expecting it to assign the class property.
Right: Use this.header = header; to explicitly target the class property.
Why? Inside the constructor, the local argument header shadows the class property of the same name. The this keyword resolves the ambiguity.
Practice Exercise
Challenge: Build a Config Class
Write a new class called myConfig with two properties: addr_width (an 8-bit value) and data_width (an 8-bit value). Give the constructor default values of 8 for addr_width and 32 for data_width. Add a display() method that prints both values. Then, in a module, create two objects: one using the defaults, and one that overrides both values to 16 and 64.
Hint
Follow the same pattern used in myPacket: declare the properties, write function new() with default argument values, use this to assign them, and write display() using $display.
Solution
class myConfig;
bit [7:0] addr_width;
bit [7:0] data_width;
function new (bit [7:0] addr_width = 8, bit [7:0] data_width = 32);
this.addr_width = addr_width;
this.data_width = data_width;
endfunction
function void display ();
$display ("addr_width = %0d, data_width = %0d", addr_width, data_width);
endfunction
endclass
module tb_top;
myConfig cfg0, cfg1;
initial begin
cfg0 = new ();
cfg0.display ();
cfg1 = new (16, 64);
cfg1.display ();
end
endmodule
Just like pkt0 and pkt1 earlier in this article, cfg0 and cfg1 are independent objects of the same class — each holds its own copy of addr_width and data_width.
Summary
In this tutorial, you learned:
- A class encapsulates properties (data) and methods (functions/tasks) into a single reusable unit
- Objects are created from a class using
new(), and each object holds its own independent copy of the class's properties - Arrays of class objects must be constructed individually, one
new()call per element - The
thiskeyword resolves ambiguity between constructor arguments and class properties of the same name
interface construct bundles related signals into a single reusable block, so connecting to a design becomes a one-line job regardless of how many signals it actually carries.What Is an Interface?
An interface is a way to encapsulate signals into a block. All related signals are grouped together to form an interface block, so the same interface can be reused across other projects. It also becomes easier to connect to the DUT and other verification components, since the connection no longer has to be made one signal at a time.
7 min read | Intermediate Level
What You'll Learn
- What a SystemVerilog interface is and the problem it solves for connecting a DUT to a testbench
- Why interface signals are typically declared
logicinstead ofwireorreg - How
modportdefines different signal directions for different components sharing the same interface - How a clocking block controls exactly when testbench signals are sampled and driven relative to a clock
A Basic Interface Example
APB bus protocol signals are put together in the interface below. Signals are declared between interface and endinterface:
interface apb_if (input pclk);
logic [31:0] paddr;
logic [31:0] pwdata;
logic [31:0] prdata;
logic penable;
logic pwrite;
logic psel;
endinterface
Why Are Signals Declared logic?
logic is a data type that lets you drive signals of this type both via assign statements and from within a procedural block. In Verilog, you could only drive a reg from a procedural block, and only drive a wire from an assign statement — but that flexibility is only one reason.
Signals connected to the DUT should support 4 states, so that X/Z values can be caught. If these signals were declared bit instead, any X or Z value would show up as a plain 0, and you'd miss the fact that the DUT ever drove an uninitialized or high-impedance value in the first place.
Quick Check
Q: If an interface signal connected to the DUT were declared bit instead of logic, and the DUT accidentally drove that signal to X, what would the testbench see?
Show Answer
It would see 0, not X. bit is a 2-state type, so any X or Z value gets silently converted to 0 — the testbench would have no way to tell an uninitialized signal apart from a legitimately-driven zero.
How Do You Define Port Directions?
Interface signals can be used within various verification components as well as the DUT, so modport is used to define signal directions. Different modport definitions can be passed to different components, letting each one see a different set of input/output directions for the very same signals:
interface myBus (input clk);
logic [7:0] data;
logic enable;
// From TestBench perspective, 'data' is input and 'enable' is output
modport TB (input data, clk, output enable);
// From DUT perspective, 'data' is output and 'enable' is input
modport DUT (output data, input enable, clk);
endinterface
SystemVerilog Modport covers this construct in more depth.
How Do You Connect an Interface to a DUT?
An interface object should be created in the top testbench module where the DUT is instantiated, and passed to the DUT. It's essential to make sure the correct modport is assigned to the DUT:
module dut (myBus busIf);
always @ (posedge busIf.clk)
if (busIf.enable)
busIf.data <= busIf.data+1;
else
busIf.data <= 0;
endmodule
// Filename : tb_top.sv
module tb_top;
bit clk;
// Create a clock
always #10 clk = ~clk;
// Create an interface object
myBus busIf (clk);
// Instantiate the DUT; pass modport DUT of busIf
dut dut0 (busIf.DUT);
// Testbench code : let's wiggle enable
initial begin
busIf.enable <= 0;
#10 busIf.enable <= 1;
#40 busIf.enable <= 0;
#20 busIf.enable <= 1;
#100 $finish;
end
endmodule
Note that dut0 is instantiated with busIf.DUT specifically — the DUT modport — while the testbench code above drives busIf.enable directly using the interface's full, undirected view.
Where Are Interfaces Used?
Interfaces are the standard way protocol testbenches (AMBA, AXI, APB, and similar) connect a reusable verification component to whatever DUT it's plugged into — the same interface and its verification IP can be reused across many different projects and DUT configurations without ever having to touch a port list.
What Are the Advantages?
Interfaces can contain tasks, functions, parameters, variables, functional coverage, and assertions. This lets you monitor and record transactions via the interface itself. It also makes connecting to the design easier regardless of how many ports it has, since all of that information is encapsulated in one interface object:
//Before interface
dut dut0 (.data (data),
.enable (enable),
// all other signals
);
// With interface - higher level of abstraction possible
dut dut0 (busIf.DUT);
How Do You Parameterize an Interface?
The same way you would for a module — letting the same interface definition adapt its signal widths to whatever design it's connected to. SystemVerilog Interface Parameters covers this in depth, including how to keep an interface's parameter and a connected design's parameter in sync.
What Are Clocking Blocks?
Signals specified inside a clocking block are sampled and driven with respect to that clock. An interface can contain multiple clocking blocks. This is specifically for testbench-related signals — it lets you control precisely when the testbench drives and samples signals from the DUT, which solves part of the race-condition problem (though not entirely). Skew values can also be parameterized:
interface my_int (input bit clk);
// Rest of interface code
clocking cb_clk @(posedge clk);
default input #3ns output #2ns;
input enable;
output data;
endclocking
endinterface
In this example, by default, inputs are sampled 3ns before the posedge of clk, and outputs are driven 2ns after the posedge of clk. SystemVerilog Clocking Blocks covers this in more depth.
Quick Check
Q: With default input #3ns output #2ns;, if clk has a posedge at 100ns, when is an input signal sampled, and when is an output signal driven?
Show Answer
The input is sampled at 97ns (3ns before the 100ns posedge), and the output is driven at 102ns (2ns after the 100ns posedge).
How Do You Use a Clocking Block?
// To wait for posedge of clock
@busIf.cb_clk;
// To use clocking block signals
busIf.cb_clk.enable = 1;
Notice that you don't have to explicitly wait for the posedge of clk before assigning 1 to enable. Because the clocking block already defines an output skew, you're assured enable will be driven 2ns after the next posedge of clk, without writing that timing logic yourself.
What It Synthesizes Into
An interface used in a design is a bundle of wires between modules. Synthesis flattens it into its individual signals, and modports only state the direction of each signal for each side. The design below connects a producer to a consumer through an interface with two modports.
interface stream_if;
logic valid, ready;
logic [7:0] data;
modport src (output valid, data, input ready);
modport dst (input valid, data, output ready);
endinterface
module producer (input logic clk, rst_n, stream_if.src s);
always_ff @(posedge clk or negedge rst_n)
if (!rst_n) begin s.valid <= 1'b0; s.data <= '0; end
else if (!s.valid || s.ready) begin s.valid <= 1'b1; s.data <= s.data + 8'd1; end
endmodule
module consumer (input logic clk, rst_n, stream_if.dst s, output logic [7:0] last);
assign s.ready = 1'b1;
always_ff @(posedge clk or negedge rst_n)
if (!rst_n) last <= '0;
else if (s.valid) last <= s.data;
endmodule
module top (input logic clk, rst_n, output logic [7:0] last);
stream_if s ();
producer p (.clk, .rst_n, .s(s));
consumer c (.clk, .rst_n, .s(s), .last);
endmodule
Synthesis result: With the default synthesis flow of ChipVerify Lab (Yosys with the SkyWater 130 nm high-density cell library), this design builds 17 flip-flops (the 8-bit counter and valid in the producer, and the 8-bit last register in the consumer) and 26 logic cells. The same design written with separate valid, ready and data ports on both modules builds exactly the same 43 cells. The interface makes the connection shorter to write and harder to get wrong, and the hardware is identical.
Common Beginner Mistakes
Mistake #1: Declaring interface signals as bit, wire, or reg
DUT-connected signals should be logic, not bit. Why? bit is 2-state and silently turns any X or Z into 0, hiding exactly the kind of uninitialized-signal bug you'd most want your testbench to catch.
Mistake #2: Passing the wrong modport when instantiating the DUT
It's easy to accidentally connect busIf.TB where busIf.DUT was intended, or vice versa. Why? Since the two modports typically define opposite signal directions for the same physical signals, passing the wrong one usually causes a direction-mismatch compile error — or worse, silently wrong behavior if the mismatch happens to compile.
Mistake #3: Driving or sampling DUT signals directly instead of through a clocking block
Accessing busIf.data directly from testbench code, instead of through a clocking block like busIf.cb_clk.data, reintroduces the exact race condition clocking blocks exist to avoid. Why? Without a defined input/output skew, whether the testbench samples a signal before or after the DUT updates it in the same time step becomes a matter of simulator scheduling order, not a well-defined outcome.
Practice Exercise
Challenge: Add a Read-Only MONITOR Modport
Using the myBus interface from earlier (signals data, enable, and clk), add a third modport called MONITOR that only ever reads signals — it should never drive anything.
Hint
A modport that only reads declares every one of its signals as input, including ones that other modports (like DUT) declare as output.
Solution
interface myBus (input clk);
logic [7:0] data;
logic enable;
modport TB (input data, clk, output enable);
modport DUT (output data, input enable, clk);
// A passive observer - every signal is an input, nothing is ever driven
modport MONITOR (input data, enable, clk);
endinterface
MONITOR declares data as input even though DUT declares it as output — each modport is just a different view of the same underlying signals, so a passive monitor component can observe everything without ever risking driving a signal it shouldn't.
Summary
In this tutorial, you learned:
- An interface bundles related signals into one reusable block, simplifying connections to the DUT and other verification components
- Interface signals are declared
logicso they support both procedural and continuous drives, and preserve 4-stateX/Zvisibility modportgives different components a different set of signal directions over the same underlying interface signals- An interface is passed into a module using the appropriate modport, such as
busIf.DUT - A clocking block defines exactly when testbench signals are sampled and driven relative to a clock, avoiding the race conditions that come from accessing DUT signals directly
Continuing the Interfaces & Modports Chapter
Continue with SystemVerilog Interface Intro, Interface Bundles, Clocking Blocks, and Modport for a deeper look at each of these topics.
SystemVerilog gives you two statements for changing a loop's flow from inside the loop. break exits the loop immediately. continue skips the rest of the current pass and moves on to the next one. Both are borrowed from C and were added in SystemVerilog. Plain Verilog-2001 had neither, and designers had to use disable on a named block to get the same effect.
6 min read | Intermediate Level
What You'll Learn
- How
breakandcontinuechange the flow of any loop - How they behave in nested loops and in
whileloops - How to use
breakto build a synthesizable "find first" circuit - Where these statements are not allowed, and what to use instead
Syntax
break; // exit the innermost enclosing loop now
continue; // skip to the next pass of the innermost enclosing loop
Both work in every SystemVerilog loop: for, foreach, while, do while, repeat and forever. Both act only on the innermost loop that contains them.
break
The loop below would normally print iterations 0 to 9. When i becomes 7, break ends the loop at once, and execution continues with the first statement after the loop.
module tb;
initial begin
// This for loop increments i from 0 to 9 and exit
for (int i = 0 ; i < 10; i++) begin
$display ("Iteration [%0d]", i);
// Let's create a condition such that the
// for loop exits when i becomes 7
if (i == 7)
break;
end
end
endmodule
ncsim> run Iteration [0] Iteration [1] Iteration [2] Iteration [3] Iteration [4] Iteration [5] Iteration [6] Iteration [7] ncsim: *W,RNQUIE: Simulation is complete.
Iteration 7 is still printed, because the $display comes before the if. The step expression i++ does not run after a break.
continue
Here, when i is 7, continue skips the $display for that pass only. The loop then carries on with 8 and 9.
module tb;
initial begin
// This for loop increments i from 0 to 9 and exit
for (int i = 0 ; i < 10; i++) begin
// Let's create a condition such that the
// for loop
if (i == 7)
continue;
$display ("Iteration [%0d]", i);
end
end
endmodule
ncsim> run Iteration [0] Iteration [1] Iteration [2] Iteration [3] Iteration [4] Iteration [5] Iteration [6] Iteration [8] Iteration [9] ncsim: *W,RNQUIE: Simulation is complete.
In a for loop, continue jumps to the step expression (i++) and then to the condition check. In a while or do while loop it jumps straight to the condition check, because those loops have no separate step.
Quick Check
Q: In the continue example, what would print if continue were replaced with break?
Show Answer
Iterations 0 to 6. When i reaches 7, break exits the loop before the $display runs, so 7, 8 and 9 never print.
break in Nested Loops
break leaves only the loop it is directly inside. The outer loop keeps running.
module tb;
initial begin
for (int row = 0; row < 3; row++) begin
for (int col = 0; col < 3; col++) begin
if (col == 1)
break; // leaves the inner (col) loop only
$display ("row %0d col %0d", row, col);
end
end
end
endmodule
// Prints: row 0 col 0, row 1 col 0, row 2 col 0
To leave both loops at once, set a flag before the inner break and test it in the outer loop. Alternatively, put the loops in a named block and use disable on it.
Using break in Digital Design
Most current synthesis tools accept break and continue inside loops with constant bounds. The loop is still unrolled. break simply turns the remaining iterations into logic that is gated off once the exit condition is met.
A "find first" circuit is a natural fit. The module below returns the index of the lowest set bit of req:
module find_first_one (
input logic [7:0] req,
output logic [2:0] idx,
output logic found
);
always_comb begin
idx = '0; // defaults when no bit is set
found = 1'b0;
for (int i = 0; i < 8; i++) begin
if (req[i]) begin
idx = i; // lowest set bit wins
found = 1'b1;
break; // stop scanning after the first match
end
end
end
endmodule
For req = 8'b0010_0110, idx is 1. Without the break, later matches would overwrite idx and the result would be the highest set bit, 5. The synthesized hardware is a priority chain from bit 0 upwards.
Where are break and continue used?
In RTL, break keeps leading-one detectors, free-slot finders in buffer allocators and first-match lookups compact and readable. In testbenches, continue skips transactions a scoreboard should ignore, such as idle cycles, and break ends a forever polling loop once a completion flag or timeout is seen.
Where break and continue Are Not Allowed
- Outside a loop. Using
breakto leave anifor abegin ... endblock is a compile error. To leave a task or function early, usereturn. - Across a
forkboundary. Abreakinside afork ... joincannot exit a loop that surrounds the fork, because each forked branch is a separate process.
Common Beginner Mistakes
Mistake #1: continue before the increment in a while loop
Wrong:
int i = 0;
while (i < 10) begin
if (i == 7) continue; // jumps back to the check with i still 7
$display ("i = %0d", i);
i++;
end
Right: increment before the continue, or use a for loop, where continue still runs the step.
Why? A while loop has no step expression. Skipping the rest of the body also skips i++, so i stays at 7 forever.
Mistake #2: Expecting break to exit every nested loop
break exits only the innermost loop. Why? It is defined relative to the nearest enclosing loop. Use a flag or disable on a named block to exit several levels at once.
Mistake #3: Using break where return belongs
Wrong: if (error) break; at the top level of a task, outside any loop
Right: if (error) return;
Why? break is only legal inside a loop. return exits the task or function from anywhere in its body.
Practice Exercise
Challenge: Sum the even values, stop at a marker
Given int data[6] = '{4, 7, 10, 3, -1, 8};, add up only the even values, and stop as soon as you reach -1, which marks the end of valid data. The expected sum is 14.
Hint
Use foreach. Check for the -1 marker first with break, then skip odd values with continue.
Solution
module tb;
int data[6] = '{4, 7, 10, 3, -1, 8};
int sum;
initial begin
foreach (data[i]) begin
if (data[i] == -1) break; // end-of-data marker: stop scanning
if (data[i] % 2 != 0) continue; // skip odd values
sum += data[i];
end
$display ("sum = %0d", sum); // sum = 14 (4 + 10); 8 is never reached
end
endmodule
The order of the two checks matters. The marker test comes first so that -1 is never treated as data.
Summary
In this tutorial, you learned:
breakexits the innermost loop immediately;continueskips to its next pass- Both work in all six SystemVerilog loops and act only on the innermost one
- In a
forloop,continuestill runs the step; in awhileloop, it jumps straight to the condition breakinside a constant-bound loop is synthesizable and gives first-match priority logic- Outside a loop, use
returnto leave a task or function, ordisableto leave a named block
An unpacked array refers to any dimension declared after the variable name. This is the opposite of a packed array, where dimensions are declared before the name and the bits are stored as one contiguous vector. Unpacked dimensions, by contrast, create separate, individually-addressable elements — each element can be a different memory word, a struct, or even another array.
Unpacked arrays cover fixed-size arrays as well as dynamic arrays, associative arrays, and queues — this article focuses on the fixed-size form, which is the most common starting point.
8 min read | Intermediate Level
What You'll Learn
- The difference between packed and unpacked array declarations
- How to declare and index single and multidimensional unpacked arrays
- How to combine packed and unpacked dimensions in one variable
- Which dimension "varies fastest" when an array is printed or flattened
Syntax
An unpacked dimension is any [size] or [msb:lsb] that appears after the variable name.
data_type array_name [size]; // single-dimensional unpacked
data_type array_name [size1] [size2]; // multidimensional unpacked
packed_type array_name [size]; // packed element, unpacked array
data_type– the element type (byte,bit,int, astruct, etc.)array_name– the identifier for the array[size]or[msb:lsb]– each pair of brackets after the name adds one more unpacked dimension
A dimension written before the name (e.g. bit [7:0] data;) is packed — it describes the bit-width of a single element. A dimension written after the name (e.g. bit data [7:0];) is unpacked — it describes how many separate elements exist. Swapping the two changes the meaning of the variable entirely.
Single Dimensional Unpacked Array
The example below declares an 8-entry stack, where each entry is one byte wide. Since [8] is written after stack, it is an unpacked dimension — SystemVerilog allocates 8 separate byte-wide elements rather than a single 8-byte packed vector.
module tb;
byte stack [8]; // depth = 8, 1 byte wide variable
initial begin
// Assign random values to each slot of the stack
foreach (stack[i]) begin
stack[i] = $random;
$display ("Assign 0x%0h to index %0d", stack[i], i);
end
// Print contents of the stack
$display ("stack = %p", stack);
end
endmodule
Output
Assign 0x24 to index 0
Assign 0x81 to index 1
Assign 0x9 to index 2
Assign 0x63 to index 3
Assign 0xd to index 4
Assign 0x8d to index 5
Assign 0x65 to index 6
Assign 0x12 to index 7
stack = '{'h24, 'h81, 'h9, 'h63, 'hd, 'h8d, 'h65, 'h12}
The foreach (stack[i]) construct walks every index of the unpacked dimension automatically, so you never have to hardcode the loop bound — useful if the array size changes later.
Unpacked arrays like this one are the natural fit for register files, FIFO/scoreboard storage in a testbench, or any structure where each entry needs to be read, written, and compared independently rather than treated as one wide bit vector.
Quick Check
Q: Is stack[0] in the example above a single bit or a full byte?
Show Answer
A full byte. The [8] is an unpacked dimension that creates 8 separate byte elements — the element type itself (byte) is what's stored at each index.
Multidimensional Unpacked Array
Adding a second set of brackets after the name creates a second unpacked dimension, effectively giving you rows and columns. The example below models a 2 × 4 array (2 rows, 4 columns), where every entry is still one byte wide.
module tb;
byte stack [2][4]; // 2 rows, 4 cols
initial begin
// Assign random values to each slot of the stack
foreach (stack[i])
foreach (stack[i][j]) begin
stack[i][j] = $random;
$display ("stack[%0d][%0d] = 0x%0h", i, j, stack[i][j]);
end
// Print contents of the stack
$display ("stack = %p", stack);
end
endmodule
Output
ncsim> run
stack[0][0] = 0x24
stack[0][1] = 0x81
stack[0][2] = 0x9
stack[0][3] = 0x63
stack[1][0] = 0xd
stack[1][1] = 0x8d
stack[1][2] = 0x65
stack[1][3] = 0x12
stack = '{'{'h24, 'h81, 'h9, 'h63}, '{'hd, 'h8d, 'h65, 'h12}}
ncsim: *W,RNQUIE: Simulation is complete.
Notice the nested foreach: the outer loop walks the first unpacked dimension (i, the rows), and the inner loop walks the second (j, the columns). This nesting order matters — see the dimension-ordering rule further down.
Packed + Unpacked Array
A single variable can mix both worlds: a packed dimension for the element's bit-width, and unpacked dimensions for how many elements exist. Here, bit [3:0][7:0] is packed (each element is a 32-bit value organized as four 8-bit bytes), and [2][4] is unpacked (2 rows of 4 such elements).
module tb;
bit [3:0][7:0] stack [2][4]; // 2 rows, 4 cols
initial begin
// Assign random values to each slot of the stack
foreach (stack[i])
foreach (stack[i][j]) begin
stack[i][j] = $random;
$display ("stack[%0d][%0d] = 0x%0h", i, j, stack[i][j]);
end
// Print contents of the stack
$display ("stack = %p", stack);
// Print content of a given index
$display("stack[0][0][2] = 0x%0h", stack[0][0][2]);
end
endmodule
Output
ncsim> run
stack[0][0] = 0x12153524
stack[0][1] = 0xc0895e81
stack[0][2] = 0x8484d609
stack[0][3] = 0xb1f05663
stack[1][0] = 0x6b97b0d
stack[1][1] = 0x46df998d
stack[1][2] = 0xb2c28465
stack[1][3] = 0x89375212
stack = '{'{'h12153524, 'hc0895e81, 'h8484d609, 'hb1f05663}, '{'h6b97b0d, 'h46df998d, 'hb2c28465, 'h89375212}}
stack[0][0][2] = 0x15
ncsim: *W,RNQUIE: Simulation is complete.
The last line, stack[0][0][2], mixes an unpacked index ([0][0] selects an element) with a packed index ([2] selects byte 2 within that 32-bit element). This is why the packed dimension is often called the "bit-select" part — it slices into an already-selected element.
Dimension Ordering: Which Index Varies Fastest?
Packed dimensions (written before the name) always vary faster than unpacked dimensions (written after the name). Within the packed group, the dimension written right next to the name varies fastest, and dimensions further away vary slower. Within the unpacked group it works the other way around: the dimension written farthest from the name (the last one declared) varies fastest, while the one immediately after the name varies slowest.
bit [1:4] m_var [1:5] // 1:4 varies faster than 1:5
bit m_var2 [1:5] [1:3] // 1:3 varies faster than 1:5
bit [1:3] [1:7] m_var3; // 1:7 varies faster than 1:3
bit [1:3] [1:2] m_var4 [1:7] [0:2] // 1:2 varies most rapidly, followed by 1:3, then 0:2 and then 1:7
This ordering is exactly why the nested foreach loops in the earlier examples were written with i (the leftmost/outer index) in the outer loop and j (the rightmost/inner index) in the inner loop — matching the loop nesting to the dimension order keeps the traversal sequential and matches how %p prints the array.
Quick Check
Q: For bit [1:3][1:2] m_var4 [1:7][0:2];, which index changes on every single iteration of a fully nested loop — the [1:7] one or the [1:2] one?
Show Answer
The [1:2] index. It's a packed dimension written right next to the variable name, so it's the fastest-varying of all four dimensions. The [1:7] unpacked dimension, being written immediately after the name (closest to it, among the unpacked dimensions), varies slowest — the [0:2] dimension, written farther from the name, is faster than [1:7] but still slower than either packed dimension.
Common Mistakes
Mistake #1: Placing the size on the wrong side of the name
Wrong intent: writing bit [8] mem; expecting 8 separate elements
Right: bit mem [8]; for 8 unpacked elements, or bit [7:0] mem; for one 8-bit packed value
Why? [8] before the name is not even legal packed-range syntax on its own (packed dimensions need an explicit [msb:lsb]), and mixing this up is one of the most common sources of "why is my array only one bit wide" confusion.
Mistake #2: Assuming a fixed-size unpacked array can grow
A declaration like byte stack [8]; is a fixed-size unpacked array — its size is set at compile time and cannot change at runtime. If you need to grow or shrink the array while the testbench runs, use a dynamic array or a queue instead.
Mistake #3: Mixing up nested foreach order with dimension order
For byte stack [2][4];, writing foreach (stack[i]) foreach (stack[i][j]) walks i (rows) in the outer loop and j (columns, the fastest-varying index) in the inner loop. Swapping this by hand-coding separate for loops in the wrong order will not cause a compile error, but it will change the sequence in which elements are visited — easy to miss in a review.
Mistake #4: Confusing a packed sub-index with an unpacked one
In bit [3:0][7:0] stack [2][4];, stack[0][0] selects a full 32-bit element (unpacked indices), while stack[0][0][2] additionally slices byte 2 out of that element (a packed index). Forgetting that the last index switches from "element select" to "bit-field select" is a common source of off-by-one confusion when debugging.
Practice Exercise
Challenge: Build a Small Register File
Declare a 4-entry unpacked array named regfile where each entry is a 16-bit packed value. Randomize every entry and print the array using %p, then print just byte 1 of regfile[2].
Hint
You need one packed dimension of [1:0][7:0] (or [15:0]) for the 16-bit width, and one unpacked dimension of [4] for the four registers.
Solution
module tb;
bit [1:0][7:0] regfile [4]; // 4 registers, 16 bits each
initial begin
foreach (regfile[i]) begin
regfile[i] = $random;
$display("regfile[%0d] = 0x%0h", i, regfile[i]);
end
$display("regfile = %p", regfile);
$display("regfile[2] byte 1 = 0x%0h", regfile[2][1]);
end
endmodule
Summary
In this tutorial, you learned:
- An unpacked dimension is any
[size]declared after the variable name, and it creates separate, individually-addressable elements - Single-dimensional unpacked arrays use one set of brackets; multidimensional ones use two or more, indexed with nested
foreachloops - A variable can combine a packed dimension (bit-width per element) with one or more unpacked dimensions (number of elements)
- Packed dimensions always vary faster than unpacked ones; within the packed group the dimension closest to the name is fastest, while within the unpacked group it's the dimension farthest from the name that's fastest
- Fixed-size unpacked arrays cannot resize at runtime — use a dynamic array or queue when the size needs to change
Quiz
No quiz questions available for this article.