Now let's take a look at some of the common ways of writing constraint expressions inside a constraint block.
14 min read | Intermediate Level
What You'll Learn
- Why only one relational operator is allowed per expression, and how to fix a variable to an exact value using
== - How
insidecompares to writing out explicit relational bounds, and its inverted form - How
:=and:/produce genuinely different weighted distributions from similar-looking numbers - Why constraint blocks all apply simultaneously rather than being processed top-to-bottom, demonstrated with two blocks that together narrow a range further than either alone
Simple Expressions
Write each relational comparison (< <= > >=) as its own expression. Chaining them in one expression compiles, but it does not mean what it looks like:
class MyClass;
rand bit [7:0] min, typ, max;
// Valid expression
constraint my_range { 0 < min;
typ < max;
typ > min;
max < 128; }
// Legal, but parsed as ((((0 < min) < typ) < max) < 128): each < yields 0 or 1
constraint my_error { 0 < min < typ < max < 128; }
// This will set min to 16 and randomize all others
constraint my_min { min == 16; }
// This will set max to a random value greater than or equal to 64
constraint my_max { max >= 64; }
endclass
You can't make assignments inside a constraint block, since it only contains expressions. Instead, use the equivalence operator ==, as shown for my_min above, where min gets a value of 16 and every other variable is randomized normally. This is one way to fix a particular value to a variable, even while the solver randomizes everything else:
constraint my_min { min == temp.low * 9/5 + 32; }
You can also use a more complex expression like this one, where min represents a variable storing Fahrenheit and low is a variable within the class object temp holding a temperature in Celsius — letting one field stay mathematically derived from another, rather than being independently randomized.
Example
class myClass;
rand bit [3:0] min, typ, max;
rand bit [3:0] fixed;
constraint my_range { 3 < min;
typ < max;
typ > min;
max < 14; }
constraint c_fixed { fixed == 5; }
function string display ();
return $sformatf ("min=%0d typ=%0d max=%0d fixed=%d", min, typ, max, fixed);
endfunction
endclass
module tb;
initial begin
for (int i = 0; i < 10; i++) begin
myClass cls = new ();
cls.randomize();
$display ("itr=%0d %s", i, cls.display());
end
end
endmodule
The fixed variable is pinned to the value 5, while the others are randomized within the bounds of my_range:
run -all; # KERNEL: itr=0 min=7 typ=9 max=12 fixed= 5 # KERNEL: itr=1 min=4 typ=9 max=12 fixed= 5 # KERNEL: itr=2 min=7 typ=10 max=13 fixed= 5 # KERNEL: itr=3 min=4 typ=6 max=11 fixed= 5 # KERNEL: itr=4 min=8 typ=12 max=13 fixed= 5 # KERNEL: itr=5 min=5 typ=6 max=13 fixed= 5 # KERNEL: itr=6 min=6 typ=9 max=13 fixed= 5 # KERNEL: itr=7 min=10 typ=12 max=13 fixed= 5 # KERNEL: itr=8 min=5 typ=11 max=13 fixed= 5 # KERNEL: itr=9 min=6 typ=9 max=11 fixed= 5 # KERNEL: Simulation has finished. There are no more test vectors to simulate. exit
Every row satisfies all three conditions at once: min greater than 3, min < typ < max, and max under 14.
Quick Check
Q: Why does 0 < min < typ < max < 128 (as written in my_error) not keep min, typ and max in order, when each individual comparison looks valid on its own?
Show Answer
Relational operators are left-associative and each one returns a 1-bit 0 or 1, so the expression is evaluated as ((((0 < min) < typ) < max) < 128). After the first comparison, the next one compares a 0 or 1 against typ, not min. Write each comparison as its own expression, implicitly ANDed with the others, exactly as my_range does.
inside Operator
You can specify a lower and upper limit as an alternative to writing out the relational expressions, using inside (covered in full depth in SystemVerilog Constraint 'inside'):
constraint my_range { typ > 32;
typ < 256; }
// typ >= 32 and typ <= 256
constraint new_range { typ inside {[32:256]}; }
// Choose from the following values
constraint spec_range { typ inside {32, 64, 128}; }
An inside range includes both its lower and upper limits. SystemVerilog gathers all the possible values and chooses among them with equal probability, unless some other constraint also applies to the same variable.
Inverted inside Operator
For any value outside a specific range, invert the constraint with !. This produces a random value from 0 to 7 (since typ is a 3-bit variable), excluding whatever falls within the specified range:
rand bit [2:0] typ;
constraint inv_range { ! (typ inside {[3:6]}); }
Repeated randomization gives every value except those falling within 3 through 6:
run -all; # KERNEL: itr=0 typ=7 # KERNEL: itr=1 typ=0 # KERNEL: itr=2 typ=7 # KERNEL: itr=3 typ=0 # KERNEL: itr=4 typ=0 # KERNEL: itr=5 typ=0 # KERNEL: itr=6 typ=7 # KERNEL: itr=7 typ=1 # KERNEL: itr=8 typ=1 # KERNEL: itr=9 typ=7 # KERNEL: Simulation has finished. There are no more test vectors to simulate. exit
Every value shown — 0, 1, and 7 — falls outside the excluded 3–6 range, exactly as the constraint requires.
Weighted Distributions
The dist operator creates weighted distributions so some values are chosen more often than others. := gives every listed value in a range that same weight individually; :/ splits a weight evenly across the values in a range.
:= Operator
rand bit [2:0] typ;
constraint dist1 { typ dist { 0:=20, [1:5]:=50, 6:=40, 7:=10}; }
In dist1, the weight of 0 is 20, 6 is 40, and 7 is 10, while each of 1 through 5 individually gets 50 — for a total weight of 20 + (5×50) + 40 + 10 = 320. The probability of choosing 0 is 20/320, and the combined probability of landing anywhere between 1 and 5 is 250/320:
class myClass;
rand bit [2:0] typ;
constraint dist1 { typ dist { 0:=20, [1:5]:=50, 6:=40, 7:=10}; }
endclass
module tb;
initial begin
for (int i = 0; i < 10; i++) begin
myClass cls = new ();
cls.randomize();
$display ("itr=%0d typ=%0d", i, cls.typ);
end
end
endmodule
Output
run -all; # KERNEL: itr=0 typ=5 # KERNEL: itr=1 typ=1 # KERNEL: itr=2 typ=6 # KERNEL: itr=3 typ=3 # KERNEL: itr=4 typ=2 # KERNEL: itr=5 typ=3 # KERNEL: itr=6 typ=0 # KERNEL: itr=7 typ=5 # KERNEL: itr=8 typ=1 # KERNEL: itr=9 typ=4 # KERNEL: Simulation has finished. There are no more test vectors to simulate. exit
Values 1 through 5 appear far more often than 0, 6, or 7 — 8 of the 10 draws land in that range, consistent with its dominant combined weight.
:/ Operator
rand bit [2:0] typ;
constraint dist2 { typ dist { 0:/20, [1:5]:/50, 6:/40, 7:/10}; }
This weight assignment (0:/20, [1:5]:/50, 6:/40, 7:/10) is what's actually used below, matching the full worked example. A version of this same snippet circulating elsewhere shows 6:/10, 7:/20 instead — those two numbers were swapped by mistake; the weights confirmed by both the worked example and its captured output are 6:/40 and 7:/10.
Here, the weight of 0 is 20, 6 is 40, and 7 is 10, while 1 through 5 share a total weight of 50 — 10 each — for a total of 20 + 50 + 40 + 10 = 120. The probability of choosing 6 is 40/120, the highest of any single value, and the probability of choosing 0 is 20/120:
class myClass;
rand bit [2:0] typ;
constraint dist2 { typ dist { 0:/20, [1:5]:/50, 6:/40, 7:/10}; }
endclass
module tb;
initial begin
for (int i = 0; i < 10; i++) begin
myClass cls = new ();
cls.randomize();
$display ("itr=%0d typ=%0d", i, cls.typ);
end
end
endmodule
Output
run -all; # KERNEL: itr=0 typ=5 # KERNEL: itr=1 typ=6 # KERNEL: itr=2 typ=4 # KERNEL: itr=3 typ=6 # KERNEL: itr=4 typ=6 # KERNEL: itr=5 typ=4 # KERNEL: itr=6 typ=2 # KERNEL: itr=7 typ=3 # KERNEL: itr=8 typ=4 # KERNEL: itr=9 typ=6 # KERNEL: Simulation has finished. There are no more test vectors to simulate. exit
6 appears more than any other single value — 4 out of 10 draws — consistent with its 40/120 weight being the highest of any individual value in the distribution.
Quick Check
Q: In dist2, is any single value in [1:5] more or less likely to be chosen than the value 7?
Show Answer
Equally likely. Each individual value in [1:5] gets 50/5 = 10 out of the shared range weight, and 7 gets 10 on its own — both work out to the same 10/120 individual probability, even though they were written using different operators.
Bidirectional Constraints
Constraint blocks aren't executed top to bottom like procedural code — every active block applies at the same time, exactly as covered in SystemVerilog Constraint Blocks. Here are two separate blocks on the same variable, combining to narrow the legal range further than either one alone:
class myClass;
rand bit [3:0] val;
constraint c1 { val > 3;
val < 12; }
constraint c2 {val >= 10; }
endclass
module tb;
initial begin
for (int i = 0; i < 10; i++) begin
myClass cls = new ();
cls.randomize();
$display ("itr=%0d typ=%0d", i, cls.val);
end
end
endmodule
c1 alone permits 4 through 11; c2 alone permits 10 and above. Together, they limit val to just 10 and 11:
run -all; # KERNEL: itr=0 typ=11 # KERNEL: itr=1 typ=11 # KERNEL: itr=2 typ=11 # KERNEL: itr=3 typ=10 # KERNEL: itr=4 typ=11 # KERNEL: itr=5 typ=10 # KERNEL: itr=6 typ=10 # KERNEL: itr=7 typ=10 # KERNEL: itr=8 typ=10 # KERNEL: itr=9 typ=10 # KERNEL: Simulation has finished. There are no more test vectors to simulate. exit
Where Is This Used?
Fixing one field to an exact value (or a value derived from another field, like the Fahrenheit-from-Celsius example above) while randomizing the rest is a common pattern for fields that need to stay mathematically consistent with something else in the same object, rather than being independently random on their own.
Common Beginner Mistakes
Mistake #1: Chaining multiple relational operators in one expression
As my_error shows, 0 < min < typ < max < 128 compiles but does not order the variables, even though each comparison looks valid individually. Why? Each < returns 0 or 1, and that result becomes the left operand of the next comparison — write the comparisons out individually, and the solver ANDs them together automatically.
Mistake #2: Trying to use = instead of == to fix a value
A constraint block only contains expressions, not procedural assignments. Why? = denotes assignment, which has no meaning inside a declarative constraint — == is the equality expression that actually pins a variable to a specific value for the solver.
Mistake #3: Confusing := with :/
As the dist1/dist2 comparison shows, these produce genuinely different distributions from very similar-looking numbers. Why? := gives every listed value that same weight individually; :/ splits one weight across an entire range — mixing them up silently changes which values actually dominate the distribution.
Mistake #4: Assuming constraint blocks are applied in the order they're written
As the bidirectional example shows, c1 and c2 combine into a single narrower range regardless of which one appears first in the source. Why? All active constraint blocks are solved as one simultaneous system — there's no sequential processing to reason about.
Practice Exercise
Challenge: Combine Two Ranges
Given constraint c1 { val >= 5; val <= 20; } and constraint c2 { val <= 12; } on the same variable, what's the combined legal range for val?
Hint
Both blocks apply simultaneously — find the overlap between what each one permits on its own.
Solution
5 through 12. c1 alone permits 5 through 20; c2 alone permits anything up to 12. The only values satisfying both at once are 5 through 12 — the same range-intersection pattern demonstrated in this article's own c1/c2 example, just with different bounds.
Summary
In this tutorial, you learned:
- Only one relational operator is allowed per constraint expression; chained comparisons must be written as separate expressions
==, not=, is how you fix a variable to a specific value inside a declarative constraint block:=assigns a weight to each listed value individually;:/divides a weight across an entire range — a small difference in syntax with a large difference in resulting distribution- All active constraint blocks on a variable apply simultaneously, and together narrow the legal range to their intersection, regardless of the order they're written in
Once you understand that constraints narrow down the space of legal random values, the natural next question is: where do constraints actually live, and how are they structured? The answer is constraint blocks — named, scoped declarations that sit inside (or alongside) a class and tell the solver what rules to follow.
14 min read | Intermediate Level
What You'll Learn
- Why constraint blocks are class members, and what that implies for inheritance and runtime control
- How multiple constraint blocks in the same class combine, and what happens when they conflict
- How to declare a constraint's body outside the class using external constraints
- How a subclass can override a parent's constraint entirely by redeclaring it with the same name
Constraint Blocks Are Class Members
A constraint block is a first-class member of a SystemVerilog class — just like a variable, function, or task. It has a name, it belongs to a class, and it participates in inheritance. This isn't just a cosmetic detail; understanding that constraints are members explains a lot of their behavior:
- They're inherited by subclasses
- They can be overridden in subclasses
- They can be individually enabled or disabled at runtime
- Multiple constraint blocks in the same class all apply simultaneously — the solver sees them all at once
The constraint solver treats every active constraint block in a class as a single logical AND of all their expressions. There's no priority or ordering among blocks by default — if you have five constraint blocks, the solver must find values that satisfy all five simultaneously.
Syntax
constraint <name_of_constraint> { <expression 1>;
// ...
<expression N>;
}
Each expression inside the braces is a condition the solver must satisfy. Multiple expressions within a single block are implicitly ANDed together. The block is terminated with a closing }, not with begin/end — constraint blocks use curly braces because they're declarative, not procedural.
- Constraint blocks must have a unique name within a class — declaring two blocks with the same name in the same class is a compile error.
- Expressions can reference multiple variables; a single block can constrain several fields at once if their values are related.
- An empty constraint block (just the name and empty braces) is legal. It compiles and runs without error, but has no effect on randomization — sometimes useful as a placeholder.
It isn't necessary to have a single constraint for every variable, nor is a constraint block restricted to conditions on only one variable. You can't, however, have conflicting constraints spread across multiple blocks, unless they're turned off using constraint_mode() — covered in SystemVerilog Disable Constraints.
Simple Constraint Block
Here's the simplest possible constraint block, to anchor the concept:
// Let's declare a new class called "Packet" with a single variable that
// can be randomized. We want this variable to have values between 2 and 6
// when randomized. This is achieved by a constraint called "c_mode" (you
// can name it anything else).
class Packet;
rand bit [3:0] mode;
constraint c_mode {
mode > 2;
mode <= 6;
}
endclass
c_mode restricts mode to the range (2, 6] — meaning values 3, 4, 5, and 6 are valid. The 4-bit variable can naturally hold 0–15, so without the constraint, all 16 of those values would be legal. With it, only 4 are.
module tb;
Packet pkt = new();
initial begin
for (int i = 0; i < 5; i++) begin
assert(pkt.randomize()) else $fatal(1, "Randomization failed");
$display("mode = %0d", pkt.mode);
end
end
endmodule
Output
mode = 6 mode = 6 mode = 5 mode = 4 mode = 5
Every value is within the legal range. Notice the assert wrapping randomize() — if the solver can't satisfy the constraints, randomize() returns 0 instead of 1. Wrapping it catches that failure immediately, rather than silently continuing with stale variable values.
Quick Check
Q: Would pkt.mode == 2 ever be a legal result from this constraint?
Show Answer
No. mode > 2 is a strict inequality, so 2 itself is excluded — only 3, 4, 5, and 6 satisfy both expressions in c_mode.
Multiple Constraint Blocks
class BusTransaction;
rand bit [31:0] addr;
rand bit [7:0] data;
rand bit [2:0] burst_len;
rand bit read_write; // 0 = read, 1 = write
// Address must be 4-byte aligned
constraint c_addr_align {
addr[1:0] == 2'b00;
}
// Address must be within a valid MMIO window
constraint c_addr_range {
addr >= 32'hF000_0000;
addr <= 32'hFACE_FACE;
}
// Burst length is 1 to 4 beats
constraint c_burst {
burst_len >= 1;
burst_len <= 4;
}
// Read transactions carry no write data
constraint c_read_data {
(read_write == 0) -> (data == 8'h0);
}
endclass
Constraint blocks are enclosed in curly braces { } instead of begin end, reflecting their declarative nature. Keeping constraints separated this way has real practical benefits:
- Readability: each block has a focused purpose, and its name tells you what it enforces.
- Selective disabling: you can turn off
c_addr_rangeindependently to test out-of-range addresses without touching the other constraints. - Inheritance and override: a subclass can override just
c_addr_rangeto work with a different memory map while inheriting the alignment and burst-length rules unchanged.
How the Solver Handles Multiple Blocks
All active constraint blocks in a class are solved simultaneously — the solver doesn't process them in order or give any one block higher priority.
Additive constraints work fine: two blocks that both restrict the same variable further narrow the valid range. In the BusTransaction example, c_addr_align and c_addr_range both apply to addr — the solver generates an address that's both aligned and within the window.
Conflicting constraints cause a solver failure. If two blocks make contradictory demands on the same variable, randomize() returns 0 — a runtime failure, not a compile error, since the simulator has no way to catch it until it actually tries to solve:
constraint c_high { addr >= 32'hFACE_FFFF; } // addr must be above facefffh
constraint c_low { addr <= 32'hF000_0000; } // addr must be below f0000000h
// These two can never both be true at once - randomize() fails
Non-conflicting additions are fine. If a second block further restricts — but doesn't contradict — an existing one, the solver simply works within the tighter window:
constraint c_range { addr >= 32'hF000_0000; addr <= 32'hFACE_FACE; }
constraint c_tighter { addr <= 32'hF400_0000; }
// Valid: the solver picks from [F000_0000, F400_0000], a subset of the first range
Quick Check
Q: If c_high were changed to a strict inequality (addr > 32'hFACE_FFFF), would it still conflict with c_low?
Show Answer
Yes. Making c_high even more restrictive can't create overlap where none existed — if the original ranges never touched, a narrower version of one of them still won't touch the other.
External Constraint Blocks
SystemVerilog also allows a constraint block's body to be defined outside the class, after the class declaration ends — called an external constraint. The mechanism is analogous to declaring a function prototype inside a class and defining it externally using the scope resolution operator ::.
Why Use External Constraints?
In large verification environments, you often want to keep the class declaration compact and push the actual constraint logic into a separate file or section. This is particularly common in UVM-based testbenches, where a base sequence class might declare constraint prototypes, and different test environments fill in the actual expressions. External constraints also let you modify constraint logic without editing the class body itself — useful when the class is owned by a shared library you don't want to touch.
Implicit External Constraint
Declared as an empty constraint (no extern keyword) inside the class:
class ABC;
rand bit [3:0] mode;
constraint c_implicit; // No "extern" keyword - implicit prototype
endclass
// External definition using :: operator
constraint ABC::c_implicit { mode > 2; }
An implicit prototype without a matching external definition isn't a compile error, but most simulators issue a warning, and the constraint simply has no effect if never defined.
Explicit External Constraint
Declared with the extern keyword inside the class:
class ABC;
rand bit [3:0] mode;
extern constraint c_explicit; // "extern" keyword - explicit prototype
endclass
// External definition - required if "extern" was used
constraint ABC::c_explicit { mode <= 6; }
With extern, failing to provide the external definition is a compile error. The extern keyword is a promise to the compiler that the definition will exist somewhere — a stricter form that catches missing definitions early.
External Constraint Example
// Let's declare a new class called "ABC" with a single variable that
// can be randomized. We want this variable to have values between 2 and 6
// when randomized. This is achieved by a constraint called "c_mode" (you
// can name it anything else).
class ABC;
rand bit [3:0] mode;
constraint c_implicit; // Implicit: won't error if body is missing
extern constraint c_explicit; // Explicit: will error if body is missing
endclass
// This is an external constraint because it is outside
// the class-endclass body of the class. The constraint
// is referenced using ::
constraint ABC::c_implicit { mode > 2; }
constraint ABC::c_explicit { mode <= 6; }
module tb;
ABC abc;
initial begin
// Create a new object with this handle
abc = new();
// In a for loop, lets randomize this class handle
// 5 times and see how the value of mode changes
// A class can be randomized by calling its "randomize()"
for (int i = 0; i < 5; i++) begin
abc.randomize();
$display ("mode = 0x%0h", abc.mode);
end
end
endmodule
Output
mode = 0x3 mode = 0x5 mode = 0x6 mode = 0x4 mode = 0x6
Both constraints apply simultaneously — mode is always greater than 2 and at most 6, regardless of whether the blocks were defined inside or outside the class. Note: it's illegal to provide multiple constraint blocks for a single prototype, or to write another block with the same name as one already used in an external prototype declaration.
Quick Check
Q: If c_explicit's external definition were accidentally left out entirely, what would happen?
Show Answer
A compile error. extern is a stricter promise than the implicit form — omitting c_implicit's body only produces a warning and a no-op constraint, but omitting c_explicit's body is caught at compile time.
Constraint Blocks and Inheritance
Because constraints are class members, they participate in SystemVerilog's inheritance model. A subclass inherits every constraint block from its parent, and can add new blocks or override an existing one by redeclaring a constraint with the same name — the child's version replaces the parent's entirely:
class BaseTransaction;
rand bit [7:0] addr;
constraint c_addr { addr inside {[8'h00 : 8'hFF]}; } // full range
endclass
class RestrictedTransaction extends BaseTransaction;
// Override: only allow the lower quarter of the address space
constraint c_addr { addr inside {[8'h00 : 8'h3F]}; }
endclass
In RestrictedTransaction, the parent's c_addr is replaced entirely, not narrowed further — 0x3F is 63, so [8'h00 : 8'h3F] covers exactly 64 of the 256 possible 8-bit values, precisely a quarter of the full range. This is a powerful pattern for building test-specific transaction types without duplicating code: define the general structure in the base class and specialize it in subclasses.
Where Is This Used?
External constraint prototypes and subclass constraint overriding are both heavily used in UVM base sequence and sequence-item classes — a shared verification component defines the structure of a transaction once, and individual tests or environments override just the value ranges they care about, without touching or duplicating the base class itself.
Common Beginner Mistakes
Mistake #1: Duplicate constraint names in the same class
Two constraint blocks with the same name in one class body is a compile error. Why? If related expressions need grouping, put them all in one block, or give each block a genuinely distinct name.
Mistake #2: Assuming constraint order matters
The solver treats every active block as one simultaneous system — writing block A before block B in the source doesn't mean A is solved first. Why? If ordering actually matters (like solving one variable before using its value to constrain another), that's handled by the dedicated solve...before construct, not by source order.
Mistake #3: Ignoring the randomize() return value
A solver failure from conflicting constraints returns 0 silently. Why? Without checking the return value, a test continues with whatever the variables last held — zero, or leftover values from a previous call — and you can spend hours debugging a test that was never exercising what you thought it was.
Mistake #4: Leaving a constraint block empty unintentionally
An empty constraint block is valid but has no effect at all. Why? If it was declared as a placeholder and never filled in, the solver won't warn you — it just quietly does nothing for that block, silently narrowing nothing.
Practice Exercise
Challenge: Override, Don't Narrow
Write a class BaseCmd with rand bit [3:0] opcode and a constraint c_op allowing the full range [0:15]. Write a subclass RestrictedCmd that overrides c_op to only allow [0:3]. If RestrictedCmd is randomized many times, what's the full range of values opcode could ever show?
Hint
Remember that redeclaring a constraint with the same name in a subclass replaces the parent's version entirely — it doesn't combine with it.
Solution
class BaseCmd;
rand bit [3:0] opcode;
constraint c_op { opcode inside {[0:15]}; }
endclass
class RestrictedCmd extends BaseCmd;
constraint c_op { opcode inside {[0:3]}; }
endclass
opcode can only ever be 0, 1, 2, or 3 — never anything from 4 to 15. Since RestrictedCmd's c_op completely replaces BaseCmd's version rather than adding to it, the parent's full-range constraint has no effect at all once overridden.
Summary
In this tutorial, you learned:
- Constraint blocks are named class members, defined with the
constraintkeyword and curly-brace bodies - All active constraint blocks in a class are solved simultaneously, as a single AND of all their expressions
- Conflicting constraints across blocks cause
randomize()to fail at runtime, not at compile time - External constraints (using
::) let a constraint's body live outside the class, withexternenforcing that the definition is actually provided - A subclass inherits every constraint block from its parent, and overriding one by name replaces it entirely rather than narrowing it further
rand and randc. Understanding exactly how each one picks values is what lets you predict — and control — how thoroughly your stimulus covers the scenarios you care about.SystemVerilog makes a class property randomizable with one of two qualifiers: rand or randc. Both apply the same way to plain variables, arrays, queues, and dynamic arrays — see SystemVerilog Array Randomization in Class for constraining array and queue sizes. The difference covered here is entirely in how repeated values are handled.
6 min read | Intermediate Level
What You'll Learn
- How
randdistributes values uniformly across its range, with repeats allowed - How
randccycles through every legal value once before any value repeats - Why
randcproperties are solved before other random variables - The practical limits of using
randcon wide variables
rand: Uniformly Distributed, Repeats Allowed
rand works the same whether the property is a scalar, a queue, or a dynamic array:
class Packet;
rand int count;
rand byte master [$];
rand bit [7:0] data [];
...
endclass
Here's the simplest case — a single 3-bit vector (bit [2:0]), randomized 10 times in a row. randomize() is called on the class object and randomizes every rand (and randc) property it finds inside that object:
class Packet;
rand bit [2:0] data;
endclass
module tb;
initial begin
Packet pkt = new ();
for (int i = 0 ; i < 10; i++) begin
pkt.randomize ();
$display ("itr=%0d data=0x%0h", i, pkt.data);
end
end
endmodule
Output
run -all; # KERNEL: itr=0 data=0x7 # KERNEL: itr=1 data=0x2 # KERNEL: itr=2 data=0x2 # KERNEL: itr=3 data=0x1 # KERNEL: itr=4 data=0x2 # KERNEL: itr=5 data=0x4 # KERNEL: itr=6 data=0x0 # KERNEL: itr=7 data=0x1 # KERNEL: itr=8 data=0x5 # KERNEL: itr=9 data=0x0 # KERNEL: Simulation has finished. There are no more test vectors to simulate.
Notice that 0x2 and 0x1 each repeat multiple times across the 10 iterations. Variables declared rand are standard random variables whose values are uniformly distributed over their range: data is a 3-bit unsigned value with a legal range of 0 through 7, so with no constraints in place, every value in that range has an equal 1-in-8 chance on every single call to randomize() — including a chance of repeating the value from the call before it.
Quick Check
Q: You call randomize() on a rand variable five times in a row and get the exact same value every time. Is something broken?
Show Answer
No — rand makes no promise against repeats. Each call is an independent, uniformly distributed pick across the legal range, so five identical results in a row are just an unlikely (but valid) outcome, not a bug.
randc: Cycles Through Every Value Before Repeating
Swap rand for randc and the declaration syntax doesn't change at all — only the value-selection behavior does:
class Packet;
randc int count;
randc byte master [$];
randc bit [1:0] data [];
...
endclass
Variables declared randc are random-cyclic: they cycle through every value in their range before any particular value repeats. We'll reuse the same class from above with one change — make data a randc variable:
class Packet;
randc bit [2:0] data;
endclass
module tb;
initial begin
Packet pkt = new ();
for (int i = 0 ; i < 10; i++) begin
pkt.randomize ();
$display ("itr=%0d data=0x%0h", i, pkt.data);
end
end
endmodule
Output
run -all; # KERNEL: itr=0 data=0x6 # KERNEL: itr=1 data=0x3 # KERNEL: itr=2 data=0x4 # KERNEL: itr=3 data=0x7 # KERNEL: itr=4 data=0x0 # KERNEL: itr=5 data=0x1 # KERNEL: itr=6 data=0x5 # KERNEL: itr=7 data=0x2 # KERNEL: itr=8 data=0x5 // Start of a new sequence # KERNEL: itr=9 data=0x0 # KERNEL: Simulation has finished. There are no more test vectors to simulate.
All eight values in the range 0 through 3'h7 are exhausted (itr=0 through itr=7) before any value repeats. At itr=8 a new cycle begins with a fresh, independently shuffled order — that's why 0x5 is allowed to show up again right away.
randc properties are solved before other random (rand) properties within the same object. This guarantees the cyclic behavior holds regardless of whatever the object's rand properties end up constrained to.
Where Is randc Used?
randc is useful when you need to guarantee coverage of a small legal set rather than just a random sample of it — for example, cycling through a small set of requester IDs when testing a round-robin arbiter, so every requester is guaranteed a turn instead of being left out by chance.
Quick Check
Q: Can the value that ends one randc cycle be the same as the value that starts the next cycle?
Show Answer
Yes. randc only guarantees no repeats within a single cycle — each cycle is shuffled independently, so a back-to-back repeat right across the cycle boundary is legal.
Common Beginner Mistakes
Mistake #1: Choosing randc for wide variables
As a randc variable's bit width grows, the solver has to remember an entire permutation of every legal value before it can start a new cycle. Why? This makes randc impractical for wide buses or large counters; reserve it for small fields such as short IDs, small mode selects, or opcode-style fields.
Mistake #2: Assuming rand won't repeat back-to-back
New users sometimes expect two consecutive calls to randomize() to always produce different values for a rand property. Why? rand is uniformly distributed with no memory of previous picks, so identical back-to-back values are a normal, expected outcome — not a sign of a stuck solver.
Mistake #3: Leaving a rand array or queue's size unconstrained
A dynamic array or queue declared rand has its length randomized too, unless you constrain it. Why? Without a size constraint you can end up with an empty array on one run and an unexpectedly large one on the next. See SystemVerilog Array Randomization in Class for how to constrain array and queue sizes.
Practice Exercise
Challenge: Watch randc Exhaust a Small Range
Declare a class property data as randc bit [1:0] (legal range 0 to 3) and randomize it 4 times in a row, printing the iteration number and value each time.
Hint
With only 4 legal values and randc, the first 4 iterations are guaranteed to produce each value exactly once — you just won't know the order until you run it.
Solution
class Packet;
randc bit [1:0] data;
endclass
module tb;
initial begin
Packet pkt = new ();
for (int i = 0 ; i < 4; i++) begin
pkt.randomize ();
$display ("itr=%0d data=0x%0h", i, pkt.data);
end
end
endmodule
Run it and you'll see all four values — 0x0, 0x1, 0x2, and 0x3 — appear exactly once across the 4 iterations, in some random order. Run it again with a different seed and the order changes, but the guarantee (every value exactly once before any repeat) does not.
Summary
In this tutorial, you learned:
randdistributes values uniformly across the legal range, and repeats are allowed on any callrandccycles through every legal value exactly once before any value can repeat, then starts a new independently shuffled cyclerandcproperties are solved before other random variables in the same objectrandandrandcapply the same way to arrays, queues, and dynamic arrays — the dedicated Array Randomization article covers constraining their sizes- Keep
randcfor small ranges; wide variables make full-cycle tracking impractical
Continuing the Randomization Chapter
Continue with pre_randomize and post_randomize, disable randomization, and randcase. For more on how the solver orders and prioritizes variables, see SystemVerilog solve before.
When verifying a digital design, one of the core challenges is generating meaningful stimulus — inputs that exercise the design the way it will be used in the real world. SystemVerilog constraints let you define the boundaries of legal behavior and let the simulator's built-in solver figure out what values to generate within those boundaries.
14 min read | Intermediate Level
What You'll Learn
- The difference between direct and randomized tests, and why constrained-random became the dominant verification methodology
- How to declare a constraint, and the difference between
randandrandc - The core constraint expression types: relational,
inside,dist, and implication - How to enable and disable constraints at runtime, and add a one-off constraint without changing the class
Direct Tests vs Randomized Tests
What Are Direct Tests?
A direct test is fully hand-crafted. You explicitly set every signal to every value, in the exact sequence you want:
// Direct test: manually drive a specific transaction
pkt.addr = 8'h10;
pkt.data = 8'hAB;
pkt.cmd = WRITE;
Direct tests are fast to write for well-understood scenarios and are great for checking a specific known bug. However, they don't scale — a moderately complex design might have hundreds of valid configurations, and writing a direct test for every combination is impractical.
What Are Randomized Tests?
A randomized test relies on the simulator to generate values automatically. The test runs repeatedly with different seeds, so each run exercises a different slice of the design's behavior:
// Randomized test: let the solver pick the values
assert(pkt.randomize());
Over many runs, randomized tests naturally exercise corner cases a human engineer simply wouldn't think to write explicitly — exactly why constrained-random verification is the dominant methodology in modern chip verification, including industry frameworks like UVM. The catch is the word constrained: purely unconstrained randomization is noisy, spending most of your simulation budget on invalid or uninteresting inputs. Constraints are how you guide the randomizer to stay in bounds.
What Is a Constraint?
A constraint narrows the space of valid random values for one or more variables. You define constraints inside a class, alongside the variables they govern. The solver reads every active constraint and picks values that satisfy all of them simultaneously:
class Packet;
rand bit [7:0] addr;
rand bit [7:0] data;
constraint addr_range { addr inside {[8'h00 : 8'h7F]}; }
endclass
randkeyword: marking a variablerandtells the solver it's a candidate for randomization. Without it,randomize()ignores the variable entirely.constraintblock: named with a label (addr_range), the body is an expression that must evaluate to true.insideoperator: restrictsaddrto the lower half of the 8-bit range.
8'h00 : 8'h7F spans exactly 128 values (0 through 127) out of the 256 possible values an 8-bit field can hold — precisely half the full range, which is why it's described as "the lower half."
The rand and randc Keywords
rand — Uniform Random
Variables declared with rand are assigned uniformly random values within the constraint space on each call to randomize(). Each call is independent — you might get the same value twice in a row:
rand bit [3:0] opcode; // any value 0-15, independently each time
randc — Random Cyclic
Variables declared with randc cycle through all possible values before repeating any — like drawing cards from a shuffled deck without replacement:
randc bit [3:0] opcode; // cycles through 0-15 before repeating
randc is particularly useful when you want guaranteed coverage of all values, not just statistically likely coverage — verifying a register address space where every address must be hit is a classic case.
Quick Check
Q: A randc bit [3:0] opcode has already produced 0, 5, 12, and 3 across its first four calls to randomize(). Could the fifth call produce 5 again?
Show Answer
No. randc guarantees no value repeats until every one of its 16 possible values (0 through 15) has been produced exactly once — with only 4 of those 16 used so far, 5 can't come up again yet.
Writing a Constraint Block
Multiple expressions inside one constraint block are treated as a logical AND — all must be satisfied:
class BusTransaction;
rand bit [7:0] addr;
rand bit [31:0] data;
rand bit [1:0] burst_len;
// addr must be 4-byte aligned
constraint align_addr { addr[1:0] == 2'b00; }
// burst_len between 1 and 3
constraint valid_burst { burst_len >= 1; burst_len <= 4; }
endclass
burst_len is only 2 bits wide, so it can never actually hold a value of 4 — the type itself already caps it at 3. The burst_len <= 4 clause is therefore redundant and never actually restricts anything beyond what the type already guarantees, even though the comment describes the intended range as "1 and 3." The constraint that actually does the work here is just burst_len >= 1.
You can also write multiple separate constraint blocks. Keeping constraints logically separated makes them easier to enable, disable, and override in subclasses — which matters as your testbench grows.
Calling randomize()
Constraints only come into play when you call randomize() on a class object. This method invokes the solver, generates new values, and returns 1 (success) or 0 (failure — meaning no valid combination existed):
Packet pkt = new();
// Correct: assert will trigger a fatal if randomize fails
assert(pkt.randomize()) else $fatal(1, "Randomization failed!");
Always check the return value. A failing randomize() is a silent killer in testbenches — ignore the return value, and your variables hold stale data from the previous call with no indication anything went wrong. If the solver can't find values satisfying every constraint simultaneously, it returns 0, typically meaning the constraints are over-specified or outright contradictory:
constraint impossible { addr > 8'hFF; } // addr is 8-bit, can never exceed 0xFF
The solver fails immediately on this — addr can never legally exceed 0xFF since that's already the maximum an 8-bit field can hold.
Constraint Expressions: A Quick Tour
Relational Constraints
constraint c1 { data < 32'h1000; }
constraint c2 { addr >= 8'h10; addr <= 8'hF0; }
The inside Operator
Restricts a variable to a set or range of values, and can be negated with !:
constraint c3 { opcode inside {READ, WRITE, IDLE}; }
constraint c4 { size inside {[4:64]}; }
constraint c5 { !(opcode inside {RESERVED_1, RESERVED_2}); }
Weighted Distributions With dist
Controls the probability weighting of different values — useful when you want a biased distribution:
constraint cmd_dist {
cmd dist { READ := 70, WRITE := 30 };
}
Use := to assign a weight to each listed item individually, or :/ to split a weight evenly across a range:
// Values 0-7 SHARE a total weight of 10; value 8 gets 50 all to itself
constraint priority_dist {
priority dist { [0:7] :/ 10, 8 := 50 };
}
The difference between := and :/ here has a much bigger practical effect than the numbers alone suggest. :/ divides its weight across the whole range, so each of the 8 individual values in [0:7] only gets 10/8 = 1.25 weight units. := gives 8 the full 50 on its own. Out of a total weight of 60, that works out to roughly 83% for value 8 and just 2% for any single value between 0 and 7 — value 8 is about 40 times more likely than any one of the others, not just "5 times" as the raw 50-vs-10 comparison might suggest.
Quick Check
Q: If priority_dist were rewritten as priority dist { [0:7] := 10, 8 := 50 }; (changing :/ to :=), would value 8 still be roughly 40 times more likely than any single value in 0-7?
Show Answer
No. With :=, every value in [0:7] individually gets the full weight of 10 — the same as value 8 gets 50. The ratio becomes 50:10, or 5 times more likely, not 40 — a completely different distribution from swapping just that one operator.
Implication Constraints
Sometimes a constraint only applies when another condition is met, using ->:
constraint read_no_data {
(cmd == READ) -> (data == 0);
}
This reads: if cmd is READ, then data must be 0. If cmd is anything else, the constraint on data simply doesn't apply.
Where Is This Used?
Constrained-random combined with coverage-driven verification is the dominant methodology for complex SoC and IP verification — UVM is built almost entirely around this pattern. A single well-constrained testbench, run across enough random seeds, routinely finds bugs that no hand-written directed test list would ever have anticipated.
Enabling and Disabling Constraints
Every named constraint block can be turned on or off at runtime with constraint_mode():
pkt.addr_range.constraint_mode(0); // disable
pkt.addr_range.constraint_mode(1); // re-enable
This is extremely useful when the same transaction class is reused across many test scenarios — write every possible constraint into the class once, and selectively activate the ones each specific test needs, rather than creating a new subclass for every variation.
Inline Constraints With randomize() with
For a one-off constraint on a single randomize() call, without modifying the class:
assert(pkt.randomize() with { addr == 8'hFF; });
The inline constraint applies on top of every existing class constraint, for that one call only — a clean way to specialize a specific test scenario without polluting the base class.
Common Beginner Mistakes
Mistake #1: Forgetting rand or randc on a variable
Without one of these, randomize() silently ignores the variable entirely. Why? The variable keeps whatever value it already held — no error, no warning, just a value that quietly never changes across calls.
Mistake #2: Writing a constraint that's redundant with the variable's own type
As the burst_len example shows, a bound that the type already enforces (like <= 4 on a 2-bit field) doesn't cause an error, but it also doesn't do what a comment or the author might have intended. Why? This kind of mismatch between stated intent and actual effect is easy to miss in review, since the constraint compiles and runs without complaint.
Mistake #3: Ignoring randomize()'s return value
A failed randomize() leaves variables holding stale data from the previous call, with nothing to indicate anything went wrong. Why? Always wrap it in an assert (or explicit check) so a contradictory or over-constrained solve fails loudly instead of silently corrupting your stimulus.
Mistake #4: Confusing := and :/ in a dist constraint
As shown above, swapping one for the other can change a distribution dramatically — not just by a small margin. Why? := applies a weight to each listed value individually; :/ splits a weight across an entire range — mixing them up produces a distribution that looks superficially similar but behaves very differently in practice.
Practice Exercise
Challenge: Combine dist and Implication
Write a class Frame with rand bit [2:0] kind (0=DATA, 1=CTRL, 2=IDLE) and rand bit [7:0] len. Add a dist constraint making DATA occur 60% of the time, CTRL 30%, and IDLE 10%. Add a second constraint requiring len to be exactly 0 whenever kind is IDLE.
Hint
The dist weights don't need to be split across a range here — each of the three kind values is a distinct, individual outcome, so := is the right operator throughout.
Solution
class Frame;
rand bit [2:0] kind;
rand bit [7:0] len;
constraint c_kind_dist {
kind dist { 0 := 60, 1 := 30, 2 := 10 };
}
constraint c_idle_len {
(kind == 2) -> (len == 0);
}
endclass
Since all three weights (60, 30, 10) apply to individual values rather than ranges, they translate directly into percentages: DATA 60% of the time, CTRL 30%, IDLE 10%. The implication constraint only takes effect when kind actually lands on IDLE (2) — for DATA or CTRL, len is left completely unconstrained by this rule.
Summary
In this tutorial, you learned:
- Constraints define the legal value space for random variables, keeping stimulus realistic instead of arbitrary
randassigns independently each call;randccycles through every value before repeating any- Relational,
inside,dist, and implication (->) constraints cover the vast majority of everyday needs, and the solver satisfies all active constraints simultaneously constraint_mode()enables and disables a named constraint block at runtime, and inlinerandomize() with {}adds a one-off constraint without touching the class- Always check
randomize()'s return value — a failed solve leaves variables silently unchanged, not reset to some obviously-wrong value
The subsequent articles in this chapter dive deeper into each of these features: constraint blocks in depth, solve...before ordering hints, foreach constraints for arrays, soft constraints, and more.
program block exists specifically to give the testbench a dedicated home that's guaranteed to run after the design has settled, plus a built-in way to know when a test has actually finished.A module is the fundamental construct for building designs — it can contain hierarchies of other modules, nets, variables, and procedural blocks describing hardware functionality. A testbench, on the other hand, is a complete environment for verifying that design, and needs its own care taken in how it's modeled: it must be properly initialized and synchronized, avoiding race conditions with the design it's testing.
7 min read | Intermediate Level
What You'll Learn
- Why the program block exists, and the specific race condition it avoids
- The program block syntax, and how multiple program blocks can share local variables
- What "simulation complete" means for a program block, and why
alwaysblocks aren't allowed inside one - How
$exitand afinalblock fit into ending a test cleanly
What Is the Need for a Program Block?
The program block was introduced for a few specific reasons:
- To provide a clear entry point for the execution of testbenches
- To create a container that holds testbench data — tasks, class objects, and functions
- To avoid race conditions with the design, by executing in the reactive region of a simulation cycle
The reactive region is one of the last phases before simulation time advances — by the time it runs, every design statement for that time step has already executed, so the testbench is guaranteed to see fully updated values. Having this clear separation between when design code runs and when testbench code runs is what makes output more deterministic across different simulators, rather than depending on scheduling details that could vary from one tool to the next.
Syntax
program [name] [port_list];
...
endprogram
Examples
program test1 (input clk, reset);
initial ...
endprogram
program test2 (interface wb_if);
initial ...
endprogram
program test3;
initial ...
endprogram
A program block can be nested within modules and interfaces, and multiple programs within the same module can share variables local to that scope. Below, mode is a local variable within tb that both p1 and p2 can access:
module tb;
bit [3:0] mode;
program p1;
...
endprogram
program p2;
...
endprogram
endmodule
Quick Check
Q: In the example above, could p1 write a value to mode and have p2 read that same value?
Show Answer
Yes. Since mode is declared in the enclosing module tb, both nested program blocks share direct access to that one variable — it isn't copied or duplicated per program block.
How Does a Program Block End Simulation?
A program block has a built-in notion of completion: once every initial block inside it has finished executing, that program block is considered to have exited — as if $exit had been called on it automatically. Once every program block in the simulation has exited this way, the simulation implicitly ends, exactly as if $finish had been called — even if your testbench never calls $finish at all.
This is especially convenient for automated regression testing: a test that's written entirely inside initial blocks in a program block will naturally stop the simulation the moment it's actually done, with no risk of the simulator hanging indefinitely waiting for something that will never happen.
Why always Blocks Aren't Allowed in a Program Block
A program block can't contain an always block (or a module, interface, or another program). This isn't an arbitrary restriction — it follows directly from how completion works. An always block runs forever by design and never reaches a natural end on its own. If one were allowed inside a program block, that block could never "finish," which would permanently block the exactly the completion mechanism described above.
If you need behavior that repeats continuously, use a forever loop inside an initial block instead — unlike an always block, a forever loop can be exited (with disable, a break, or simply reaching the end of its enclosing process), so the program block can still complete normally when the test decides it's done.
Quick Check
Q: Why does a forever loop inside an initial block work fine in a program block, while an always block doesn't?
Show Answer
Because a forever loop runs inside a process (the initial block) that can still be terminated from the outside — via disable, for instance — letting that initial block eventually reach completion. An always block has no equivalent way to be stopped; it's designed to run for the entire simulation, which is incompatible with a program block's completion model.
Ending a Program Early: $exit
$exit lets one specific program block signal that it's done, without necessarily ending the entire simulation if other program blocks are still active. $finish, by contrast, ends the whole simulation immediately, regardless of what any program block is doing. A final block — allowed in both modules and programs — runs once, right at the very end of simulation, and is commonly used for printing a summary of errors and warnings; it can't contain delays or other timing controls, since it has to execute in zero time.
Where Is a Program Block Used?
A typical testbench structure uses a single top-level program block to house the main test sequence — class objects, the top-level task calls, and the overall flow — while the DUT lives in its own module, connected through an interface. This keeps the "what the test does" code cleanly separated from "what the hardware does," with the reactive-region scheduling guarantee applying automatically to everything inside the program.
Common Beginner Mistakes
Mistake #1: Putting an always block inside a program block
As explained above, this isn't allowed and won't compile. Why? An always block never terminates on its own, which is fundamentally incompatible with a program block's simulation-completion model — use a forever loop inside an initial block instead.
Mistake #2: Assuming $finish must always be called explicitly
Once every program block's initial blocks have completed, simulation ends on its own. Why? It's still perfectly fine to call $finish explicitly — for clarity, or to end a test early — but it's not required just to bring a normal test to a close.
Mistake #3: Trying to instantiate a design module inside a program block
A program block can't contain a module, an interface, or another program. Why? Program blocks exist to hold testbench code — tasks, functions, class objects, and initial blocks — not design hierarchy; the DUT and any interfaces need to be instantiated in an enclosing module instead, with only a handle or port connection passed into the program block.
Practice Exercise
Challenge: Predict When Simulation Ends
A single program block contains two initial blocks: one that runs for 50ns before finishing, and another that runs for 80ns before finishing. Assuming neither one calls $finish explicitly, at what time does the simulation end?
Hint
Simulation only ends once every initial block in every program block has completed — not just the first one.
Solution
80ns. The program block as a whole doesn't exit until both of its initial blocks have finished, and the slower of the two determines when that happens — the 50ns block finishing first doesn't end anything on its own.
Summary
In this tutorial, you learned:
- A program block gives testbench code a dedicated home that executes in the reactive region, after all design activity for that time step has settled — avoiding race conditions between design and testbench code
- Program blocks can accept ports or interfaces, and multiple program blocks nested in the same module can share that module's local variables
- A program block implicitly exits once all of its
initialblocks complete; once every program block has exited, simulation ends automatically, without needing an explicit$finish alwaysblocks (along with modules, interfaces, and other programs) aren't allowed inside a program block, since they never terminate on their own — use aforeverloop inside aninitialblock instead$exitends one specific program block;$finishends the whole simulation; afinalblock runs once at the very end, commonly for summary reporting
Continuing the Testbench Components Chapter
Continue with SystemVerilog Command Line Arguments.
Quiz
No quiz questions available for this article.