SystemVerilog prohibits a class declared as virtual from being directly instantiated — this is called an abstract class. However, an abstract class can still be extended to form other sub-classes, which can then be instantiated normally. This is useful for enforcing that testcase developers always extend a base class to form another class for their needs — so base classes are commonly declared virtual, though it isn't mandatory.
11 min read | Intermediate Level
What You'll Learn
- What makes a class "abstract" in SystemVerilog, and why it can't be instantiated directly
- How an abstract class can still be extended into usable subclasses
- What a pure virtual method is, and why its implementation is mandatory in every subclass
- Why abstract base classes are a common pattern for enforcing a required interface
Syntax
virtual class
// class definition
endclass
A Normal Class
For comparison, here's an ordinary class, instantiated normally:
class BaseClass;
int data;
function new();
data = 32'hc0de_c0de;
endfunction
endclass
module tb;
BaseClass base;
initial begin
base = new();
$display ("data=0x%0h", base.data);
end
endmodule
Output
ncsim> run data=0xc0dec0de ncsim: *W,RNQUIE: Simulation is complete.
Making It Abstract With virtual
Declaring the exact same class virtual turns it into an abstract class:
virtual class BaseClass;
int data;
function new();
data = 32'hc0de_c0de;
endfunction
endclass
module tb;
BaseClass base;
initial begin
base = new();
$display ("data=0x%0h", base.data);
end
endmodule
Output
base = new(); | ncvlog: *E,CNIABC (testbench.sv,12|5): An abstract (virtual) class cannot be instantiated.
The exact same code that worked a moment ago now fails to compile, purely because of the added virtual keyword on the class declaration.
Quick Check
Q: Would using a typed constructor, like BaseClass base = BaseClass::new;, avoid this error?
Show Answer
No. The restriction is on the class itself — it's abstract, so no syntax for directly constructing a BaseClass object will work. The only way around it is to extend the class and instantiate the subclass instead.
Extending an Abstract Class
Abstract classes can be extended just like any other SystemVerilog class, using extends:
virtual class BaseClass;
int data;
function new();
data = 32'hc0de_c0de;
endfunction
endclass
class ChildClass extends BaseClass;
function new();
data = 32'hfade_fade;
endfunction
endclass
module tb;
ChildClass child;
initial begin
child = new();
$display ("data=0x%0h", child.data);
end
endmodule
Output
ncsim> run data=0xfadefade ncsim: *W,RNQUIE: Simulation is complete.
ChildClass's constructor never writes super.new() explicitly, but since BaseClass's constructor takes no required arguments, SystemVerilog still calls it implicitly first — briefly setting data to 0xc0dec0de — before ChildClass's own constructor body runs and immediately overwrites it to 0xfadefade. See SystemVerilog Class Constructor for more on this implicit-call behavior.
Quick Check
Q: If ChildClass's constructor body were completely empty, what would child.data show?
Show Answer
0xc0dec0de. With no explicit body to overwrite it, the implicitly-called base constructor's assignment would be the only thing setting data, and it would simply remain at that value.
Pure Virtual Methods
A virtual method inside an abstract class can be declared with the keyword pure, making it a pure virtual method. Such a method only specifies a prototype within the abstract class — no body at all — and its actual implementation is left entirely to the subclasses that extend it.
Pure Method Example
virtual class BaseClass;
int data;
pure virtual function int getData();
endclass
class ChildClass extends BaseClass;
virtual function int getData();
data = 32'hcafe_cafe;
return data;
endfunction
endclass
module tb;
ChildClass child;
initial begin
child = new();
$display ("data = 0x%0h", child.getData());
end
endmodule
The pure virtual method's prototype and its implementation must share the same arguments and return type.
Output
ncsim> run data = 0xcafecafe ncsim: *W,RNQUIE: Simulation is complete.
Notice BaseClass's getData() declaration ends right at the semicolon — no endfunction, no body at all. All of the actual logic lives entirely inside ChildClass's own implementation.
Quick Check
Q: If ChildClass didn't implement getData() at all, could child = new(); still succeed?
Show Answer
No. A class that inherits a pure virtual method without providing its own implementation remains abstract itself — the same restriction that blocks instantiating BaseClass directly would apply to ChildClass too, until every inherited pure virtual method has a concrete implementation somewhere in the chain.
Where Are Abstract Classes Used?
Abstract base classes with pure virtual methods are a common way to guarantee a required interface across every component in a verification environment — forcing every user-written driver, monitor, or scoreboard extension to provide a specific method, catching a missing implementation as a compile-time error instead of a confusing gap discovered only at run time.
Common Beginner Mistakes
Mistake #1: Trying to directly instantiate an abstract class
As the second example shows, this is always a compile-time error, regardless of what syntax is used to attempt it. Why? An abstract class exists specifically to be extended, not instantiated on its own — the whole point is to force every actual object to come from a more specific subclass.
Mistake #2: Forgetting that extending an abstract class still runs its constructor
Even without writing super.new() explicitly, the base class's own constructor logic still runs first, as the "Extending an Abstract Class" example shows. Why? This can be surprising if the base constructor has a side effect (like the counters covered in earlier articles) that the child class doesn't expect to happen automatically.
Mistake #3: Trying to give a pure virtual method a body
A pure virtual method's declaration in the abstract class ends at the semicolon — adding a body there is a compile-time error. Why? The entire point of pure is that the implementation is mandatory in a subclass, not optional in the base class — providing a body in the base would defeat that requirement.
Mistake #4: Leaving a pure virtual method unimplemented in a subclass
As the third Quick Check shows, this leaves the subclass abstract too, blocking its own instantiation. Why? Every pure virtual method inherited from a base class needs a real implementation somewhere in the chain before any concrete object can actually be constructed.
Practice Exercise
Challenge: Two Pure Virtual Methods
Extend BaseClass with a second pure virtual method, getDoubled(), that should return data multiplied by 2. Implement both methods in ChildClass, and predict the output of calling each.
Hint
Both methods need their own prototype-only declaration in the abstract base class, and both need a full implementation in the child class — leaving either one unimplemented would keep ChildClass abstract too.
Solution
virtual class BaseClass;
int data;
pure virtual function int getData();
pure virtual function int getDoubled();
endclass
class ChildClass extends BaseClass;
virtual function int getData();
data = 32'hcafe_cafe;
return data;
endfunction
virtual function int getDoubled();
return data * 2;
endfunction
endclass
module tb;
ChildClass child;
initial begin
child = new();
$display ("data = 0x%0h", child.getData());
$display ("doubled = 0x%0h", child.getDoubled());
end
endmodule
The first call sets and returns 0xcafecafe, exactly as before. The second call reads the now-set data and returns 0x95fd95fc — double 0xcafecafe, wrapped within the 32-bit width of int — confirming both pure virtual methods needed independent implementations before ChildClass could be instantiated at all.
Summary
In this tutorial, you learned:
- A class declared
virtualbecomes abstract, and cannot be directly instantiated — only extended - Extending an abstract class still runs its constructor logic, even without an explicit
super.new()call, as long as the base constructor requires no arguments - A
pure virtualmethod has only a prototype in the abstract class, with no body — the implementation is mandatory in a subclass - A subclass that doesn't implement every inherited pure virtual method remains abstract itself, and can't be instantiated either
- Abstract classes with pure virtual methods are a common way to enforce a required interface across every component that extends them
Just like static variables in a class, constraints can be declared static. A static constraint is shared across every instance of the class — but only in one specific sense: how it responds to being turned on or off.
Constraints are affected by the static keyword only through constraint_mode(). When a non-static constraint is turned off, it's turned off only for the specific instance that made the call. When a static constraint is turned off, it's turned off for every instance of the class at once.
13 min read | Intermediate Level
What You'll Learn
- What makes a static constraint different from the default (non-static) kind
- Why
constraint_mode()only affects one instance for a non-static constraint, but every instance for a static one - How to verify the difference concretely, using one class with both a static and a non-static constraint side by side
Syntax
A constraint block is declared static by including the static keyword in its definition:
class [class_name];
...
static constraint [constraint_name] [definition]
endclass
Non-static Constraints
Constraints are non-static by default, so a separate copy exists for each class instance. Here, both constraints on a are ordinary, non-static blocks:
class ABC;
rand bit [3:0] a;
// Both are non-static constraints
constraint c1 { a > 5; }
constraint c2 { a < 12; }
endclass
module tb;
initial begin
ABC obj1 = new;
ABC obj2 = new;
for (int i = 0; i < 5; i++) begin
obj1.randomize();
obj2.randomize();
$display ("obj1.a = %0d, obj2.a = %0d", obj1.a, obj2.a);
end
end
endmodule
Both constraints are active in both instances, so both consistently land in the range (5, 12):
ncsim> run obj1.a = 9, obj2.a = 6 obj1.a = 7, obj2.a = 11 obj1.a = 6, obj2.a = 6 obj1.a = 9, obj2.a = 11 obj1.a = 6, obj2.a = 9 ncsim: *W,RNQUIE: Simulation is complete.
Static Constraints
Now let's turn off a non-static constraint and compare it against turning off a static one, using the exact same class with one of each.
Turn Off a Non-static Constraint
Here, c1 stays non-static, but c2 is declared static. Only obj1's copy of c1 is disabled:
class ABC;
rand bit [3:0] a;
// "c1" is non-static, but "c2" is static
constraint c1 { a > 5; }
static constraint c2 { a < 12; }
endclass
module tb;
initial begin
ABC obj1 = new;
ABC obj2 = new;
// Turn off non-static constraint
obj1.c1.constraint_mode(0);
for (int i = 0; i < 5; i++) begin
obj1.randomize();
obj2.randomize();
$display ("obj1.a = %0d, obj2.a = %0d", obj1.a, obj2.a);
end
end
endmodule
Output
ncsim> run obj1.a = 3, obj2.a = 6 obj1.a = 7, obj2.a = 11 obj1.a = 6, obj2.a = 6 obj1.a = 9, obj2.a = 11 obj1.a = 6, obj2.a = 9 ncsim: *W,RNQUIE: Simulation is complete.
obj1 produces a value (3) outside c1's a > 5 range — confirming c1 is genuinely off for that instance. obj2's values all stay within (5, 12) throughout, showing its own copy of c1 was never touched.
Quick Check
Q: If obj2.c1.constraint_mode(0) were also called, would that affect obj1 in any way?
Show Answer
No. c1 is non-static, so each instance has a completely independent copy of it — disabling obj2's copy has no effect on obj1's, whether obj1's copy is currently enabled or already disabled.
Turn Off a Static Constraint
This time, the static constraint c2 is disabled — through obj1's handle, but since c2 is static, both instances should be affected:
class ABC;
rand bit [3:0] a;
// "c1" is non-static, but "c2" is static
constraint c1 { a > 5; }
static constraint c2 { a < 12; }
endclass
module tb;
initial begin
ABC obj1 = new;
ABC obj2 = new;
// Turn off static constraint
obj1.c2.constraint_mode(0);
for (int i = 0; i < 5; i++) begin
obj1.randomize();
obj2.randomize();
$display ("obj1.a = %0d, obj2.a = %0d", obj1.a, obj2.a);
end
end
endmodule
Output
ncsim> run obj1.a = 15, obj2.a = 12 obj1.a = 9, obj2.a = 15 obj1.a = 14, obj2.a = 6 obj1.a = 11, obj2.a = 11 obj1.a = 12, obj2.a = 11 ncsim: *W,RNQUIE: Simulation is complete.
Both objects show values exceeding 11 (15, 14, 12 on obj1; 12, 15 on obj2), confirming c2 is genuinely off for both — even though the call was made through obj1's handle alone. c1 (still active, still non-static) continues to keep every value above 5 on both sides.
Quick Check
Q: If a third object, obj3, were constructed after obj1.c2.constraint_mode(0) was called, would obj3's copy of c2 be active or disabled?
Show Answer
Disabled. A static constraint's mode is shared across the entire class, not tied to which instances existed at the time the mode was changed — any instance, including ones created afterward, shares that same static state.
Where Is This Used?
A static constraint fits a rule that should never be selectively bypassed on a per-instance basis — a hard protocol-wide legality boundary, for instance — while still allowing that rule to be switched off entirely for a specific debug scenario or formal setup with a single constraint_mode() call, rather than looping through every existing object individually.
Common Beginner Mistakes
Mistake #1: Assuming static changes how the constraint itself behaves
The static keyword doesn't change the constraint's own logic during randomization at all — both examples still enforce a < 12 identically while c2 is enabled. Why? What static actually changes is purely how constraint_mode() propagates when the constraint is toggled on or off, nothing about the constraint expression itself.
Mistake #2: Assuming disabling a non-static constraint affects other instances
As the first Quick Check shows, it doesn't — each instance has a fully independent copy. Why? Non-static is the default specifically because most constraints are meant to apply per-object, not shared class-wide.
Mistake #3: Forgetting a static constraint's mode change reaches every instance
As the second Quick Check shows, this includes instances created after the mode change, not just ones that already existed. Why? There's only one shared enable/disable state for a static constraint, regardless of how many objects of the class exist or when they were constructed.
Mistake #4: Confusing a static constraint with a static class property
A static class property shares one actual value across every instance; a static constraint shares its enable/disable state, not any value. Why? Constraints don't hold values the way properties do — the only thing static actually shares here is whether the constraint is currently active.
Practice Exercise
Challenge: Disable Through a Different Instance
Given a class with static constraint c_range { val inside {[10:20]}; } and three instances, obj_a, obj_b, and obj_c, predict what happens to obj_a and obj_c after calling obj_b.c_range.constraint_mode(0);.
Hint
It doesn't matter which specific instance's handle is used to call constraint_mode() on a static constraint — only that some instance made the call.
Solution
Both obj_a and obj_c lose the [10:20] restriction too. Since c_range is static, its enable/disable state is shared across the entire class — disabling it through obj_b's handle disables it everywhere, exactly as if it had been called through obj_a or obj_c instead.
Summary
In this tutorial, you learned:
- Constraints are non-static by default, with each class instance holding its own independent copy
- A constraint declared
staticshares its enable/disable state across every instance of the class - Disabling a non-static constraint through one instance's handle has no effect on any other instance
- Disabling a static constraint through any single instance's handle disables it for every instance, including ones created afterward
staticonly changes howconstraint_mode()propagates — it has no effect on the constraint's own logic while active
The SystemVerilog constraint solver, by default, tries to give a uniform distribution across the entire space of valid combinations — not necessarily a uniform distribution for each individual variable on its own. solve...before can change that, shifting probability so certain corner cases get chosen far more often than they otherwise would. This article compares an example with and without it.
14 min read | Intermediate Level
What You'll Learn
- Why the solver aims for a uniform distribution across the whole solution space by default, not independently for each variable
- How that default behavior can make one variable's value far less likely than you might expect, just because it happens to leave fewer combinations available
solve...before, and how it gives a variable an independent, even distribution instead- The restrictions on which variables can be ordered this way
Random Distribution Example
A 3-bit random variable b has 8 legal values, and the probability of b landing on any one of them is the same:
class ABC;
rand bit [2:0] b;
endclass
module tb;
initial begin
ABC abc = new;
for (int i = 0; i < 10; i++) begin
abc.randomize();
$display ("b=%0d", abc.b);
end
end
endmodule
Output
ncsim> run b=7 b=7 b=2 b=1 b=6 b=4 b=2 b=4 b=0 b=1 ncsim: *W,RNQUIE: Simulation is complete.
Repeated values in the output don't mean anything special — a previous randomization has no effect on the current one, so the randomizer is free to pick any of the 8 values regardless of what came before. Every one of the 8 legal values has an equal chance of being chosen.
Without solve...before
Now consider two random variables, where the constraint ensures b gets 0x3 whenever a is 1:
class ABC;
rand bit a;
rand bit [1:0] b;
constraint c_ab { a -> b == 3'h3; }
endclass
module tb;
initial begin
ABC abc = new;
for (int i = 0; i < 8; i++) begin
abc.randomize();
$display ("a=%0d b=%0d", abc.a, abc.b);
end
end
endmodule
Output
ncsim> run a=0 b=0 a=0 b=1 a=0 b=0 a=0 b=1 a=0 b=2 a=1 b=3 a=0 b=3 a=0 b=3 ncsim: *W,RNQUIE: Simulation is complete.
a and b are determined together, not one after the other. When a is 0, b can take any of 4 values — 4 valid combinations. When a is 1, b can only be 3 — just 1 valid combination. That's 5 valid (a, b) pairs total, and by default the solver treats all 5 as equally likely:
| a | b | Probability |
|---|---|---|
| 0 | 0 | 1/5 (20%) |
| 0 | 1 | 1/5 (20%) |
| 0 | 2 | 1/5 (20%) |
| 0 | 3 | 1/5 (20%) |
| 1 | 3 | 1/5 (20%) |
Because only 1 of those 5 equally-likely combinations has a=1, the overall probability of a ending up 1 is just 1/5, or 20% — noticeably less than the 50/50 you might expect from a single-bit variable on its own.
Quick Check
Q: If b were 3 bits wide (8 possible values) instead of 2, with the same a -> b == 7 style constraint, would P(a=1) go up or down compared to this 20% example?
Show Answer
Down — to 1/9, about 11%. There would be 8 valid combinations with a=0 (one per value of b) plus 1 with a=1, for 9 total. A wider b means more combinations share the "pie," shrinking a=1's relative share even further.
With solve...before
SystemVerilog lets you order variables so one is chosen independently of another, using the solve keyword:
class ABC;
rand bit a;
rand bit [1:0] b;
constraint c_ab { a -> b == 3'h3;
// Tells the solver that "a" has
// to be solved before attempting "b"
// Hence value of "a" determines value
// of "b" here
solve a before b;
}
endclass
module tb;
initial begin
ABC abc = new;
for (int i = 0; i < 8; i++) begin
abc.randomize();
$display ("a=%0d b=%0d", abc.a, abc.b);
end
end
endmodule
Output
ncsim> run a=1 b=3 a=1 b=3 a=0 b=1 a=0 b=0 a=0 b=0 a=0 b=1 a=1 b=3 a=0 b=2 ncsim: *W,RNQUIE: Simulation is complete.
Compare this against the previous output — a=1 now shows up far more often. a is solved first, and whatever it gets determines how b is solved next:
| a | b | Probability |
|---|---|---|
| 0 | 0 | 1/2 × 1/4 = 1/8 (12.5%) |
| 0 | 1 | 1/2 × 1/4 = 1/8 (12.5%) |
| 0 | 2 | 1/2 × 1/4 = 1/8 (12.5%) |
| 0 | 3 | 1/2 × 1/4 = 1/8 (12.5%) |
| 1 | 3 | 1/2 (50%) |
Because a is now solved on its own, the probability of it landing on either 0 or 1 is a flat 50%. Only once a is settled does the solver work out b — freely among 4 values if a=0 (each getting a quarter of that 50%, or 12.5% overall), or forced straight to 3 if a=1 (keeping the whole 50%, since there's nothing left to choose). P(a=1) has jumped from 20% to 50%, exactly the shift solve...before is meant to produce.
Quick Check
Q: With solve a before b, does the constraint a -> b == 3'h3 still hold in every generated combination?
Show Answer
Yes. solve...before only changes the probability weighting among already-legal combinations — it never makes an illegal combination possible or removes a legal one. Every row in both probability tables still satisfies the original constraint.
Restrictions
A few restrictions apply to solve...before:
randcvariables aren't allowed, since they're always solved first regardless- Variables should be integral values
- There must be no circular dependency in the ordering, such as
solve a before bcombined withsolve b before a
Where Is This Used?
solve...before is commonly used to boost the probability of a specific, interesting corner case — like an error-injection condition — that would otherwise get drowned out by the sheer number of "normal" combinations in the total solution space. Exactly the a=1 (error case) versus a=0 (normal case) pattern demonstrated in this article.
Common Beginner Mistakes
Mistake #1: Assuming every legal value is independently equally likely by default
As the "Without solve...before" example shows, the solver aims for uniform distribution across the entire joint solution space, not per variable. Why? A variable's value can end up much rarer than expected if it happens to correspond to fewer overall valid combinations than its alternatives.
Mistake #2: Assuming solve...before changes which values are legal
As the second Quick Check shows, it doesn't — the constraint still holds in every case. Why? solve...before only re-weights the probability among combinations that were already valid; it has no effect on legality at all.
Mistake #3: Trying to order a randc variable with solve...before
This isn't allowed. Why? A randc variable is always solved first regardless of any ordering hint, since its cyclic behavior depends on being resolved independently of everything else.
Mistake #4: Creating a circular solve...before ordering
solve a before b combined with solve b before a is illegal. Why? The solver needs a well-defined order to resolve variables in — a circular dependency gives it no valid starting point.
Practice Exercise
Challenge: Compute the Probability Shift
Given rand bit a;, rand bit [2:0] b; (3 bits this time), and constraint c { a -> b == 3'h7; }, compute P(a=1) both without and with solve a before b;.
Hint
Without solve...before, count the total valid (a,b) combinations and treat them as equally likely. With it, a is solved independently first.
Solution
Without solve...before: P(a=1) = 1/9 ≈ 11.1%. There are 8 valid combinations with a=0 (one per value of b) and 1 with a=1, for 9 total, all equally likely.
With solve a before b;: P(a=1) = 50%. Once a is solved on its own with a flat 50/50 split, b is resolved afterward — forced to 7 whenever a=1, so that entire 50% stays intact regardless of how many values b could otherwise take.
Summary
In this tutorial, you learned:
- By default, the constraint solver aims for a uniform distribution across the entire joint solution space, not independently for each variable
- This can make a variable's value much less likely than expected if it corresponds to fewer overall valid combinations than its alternatives
solve a before b;givesaan independent, even distribution, then resolvesbbased on whateveraturned out to besolve...beforechanges probability weighting only — it never changes which combinations are actually legalrandcvariables can't be ordered withsolve...before, and circular orderings are illegal
SystemVerilog supports using a foreach loop inside a constraint block, so entire arrays can be constrained with a single rule instead of writing out one expression per element. The foreach construct iterates over an array's elements, with its argument acting as an identifier representing a single entity in the array (see SystemVerilog Loops for a refresher on foreach outside of constraints).
15 min read | Intermediate Level
What You'll Learn
- How
foreachinside a constraint lets you constrain every element of an array with one rule - Why dynamic arrays and queues need their size established before or within the constraint, unlike fixed-size arrays
- How nested
foreachloops reach into multidimensional arrays, including packed sub-dimensions - How array reduction methods like
sum()can be used directly inside a constraint with thewithclause
Basic foreach Constraint
Here, a static array of 5 elements is constrained so each element equals its own index:
class ABC;
rand bit[3:0] array [5];
// This constraint will iterate through each of the 5 elements
// in an array and set each element to the value of its
// particular index
constraint c_array { foreach (array[i]) {
array[i] == i;
}
}
endclass
module tb;
initial begin
ABC abc = new;
abc.randomize();
$display ("array = %p", abc.array);
end
endmodule
Output
ncsim> run
array = '{'h0, 'h1, 'h2, 'h3, 'h4}
ncsim: *W,RNQUIE: Simulation is complete.
Each element is assigned a value equal to its own index — not one shared random value applied to all 5 elements, but 5 independently-generated values, each following the rule expressed in the loop body.
Quick Check
Q: If the array were declared bit[3:0] array[8] instead of [5], what would array[7] be constrained to?
Show Answer
7. The rule array[i] == i applies to every index the foreach loop reaches, regardless of the array's actual size — each element still just equals its own index.
Dynamic Arrays and Queues
Dynamic arrays and queues don't have a size at the time of declaration, so foreach can't be used directly until that size is established — either by assigning it directly, or by constraining it as part of the same set of constraints:
class ABC;
rand bit[3:0] darray []; // Dynamic array -> size unknown
rand bit[3:0] queue [$]; // Queue -> size unknown
// Assign size for the queue if not already known
constraint c_qsize { queue.size() == 5; }
// Constrain each element of both the arrays
constraint c_array { foreach (darray[i])
darray[i] == i;
foreach (queue[i])
queue[i] == i + 1;
}
// Size of an array can be assigned using a constraint like
// we have done for the queue, but let's assign the size before
// calling randomization
function new ();
darray = new[5]; // Assign size of dynamic array
endfunction
endclass
module tb;
initial begin
ABC abc = new;
abc.randomize();
$display ("array = %p\nqueue = %p", abc.darray, abc.queue);
end
endmodule
Output
ncsim> run
array = '{'h0, 'h1, 'h2, 'h3, 'h4}
queue = '{'h1, 'h2, 'h3, 'h4, 'h5}
ncsim: *W,RNQUIE: Simulation is complete.
Two different approaches to sizing are shown side by side: darray's size is fixed directly in the constructor (new[5]), before randomization ever runs, while queue's size is fixed through its own constraint (queue.size() == 5), letting the solver establish it as part of the same solve.
Quick Check
Q: Would foreach (queue[i]) queue[i] == i + 1; work correctly if c_qsize were removed entirely?
Show Answer
No — queue would have no established size for foreach to iterate over. The size has to be pinned down somewhere, either through a constraint like c_qsize or a direct assignment, before a foreach constraint on its elements makes sense.
Multidimensional Arrays
SystemVerilog constraints are powerful enough to apply to multidimensional arrays too, including ones that mix packed and unpacked dimensions. Here, each element of a 3×5 unpacked array is itself a 20-bit packed value, structured as five 4-bit nibbles:
The constraint sets alternating nibbles to 0xF and 0, producing the pattern 0xF0F0F in every element:
class ABC;
rand bit[4:0][3:0] md_array [3][5]; // Multidimensional Arrays
constraint c_md_array {
foreach (md_array[i]) {
foreach (md_array[i][j]) {
foreach (md_array[i][j][k]) {
if (k %2 == 0)
md_array[i][j][k] == 'hF;
else
md_array[i][j][k] == 0;
}
}
}
}
endclass
module tb;
initial begin
ABC abc = new;
abc.randomize();
$display ("md_array = %p", abc.md_array);
end
endmodule
Output
ncsim> run
md_array = '{'{'hf0f0f, 'hf0f0f, 'hf0f0f, 'hf0f0f, 'hf0f0f}, '{'hf0f0f, 'hf0f0f, 'hf0f0f, 'hf0f0f, 'hf0f0f}, '{'hf0f0f, 'hf0f0f, 'hf0f0f, 'hf0f0f, 'hf0f0f}}
ncsim: *W,RNQUIE: Simulation is complete.
The nesting order matters here: the first two foreach levels (i, then j) walk the array's unpacked dimensions, in the same order they appear in the declaration ([3][5]). The third level (k) then reaches into the element's own packed dimension ([4:0]), letting the constraint address individual nibbles within each 20-bit value. With k running 0 through 4, the even indices land on 0xF and the odd ones on 0 — exactly the alternating pattern that produces 0xF0F0F.
Quick Check
Q: Which array dimension does foreach (md_array[i][j][k])'s k actually iterate over — an unpacked dimension, or the packed one?
Show Answer
The packed dimension, [4:0]. The first two foreach levels already consumed both unpacked dimensions ([3] and [5]); the third level goes one level deeper, into the packed structure of each individual element.
Multidimensional Dynamic Arrays
Constraining a multidimensional dynamic array is trickier, and support varies by simulator. Here, neither dimension of a 2D array has a known size up front:
class ABC;
rand bit[3:0] md_array [][]; // Multidimensional Arrays with unknown size
constraint c_md_array {
// First assign the size of the first dimension of md_array
md_array.size() == 2;
// Then for each sub-array in the first dimension do the following:
foreach (md_array[i]) {
// Randomize size of the sub-array to a value within the range
md_array[i].size() inside {[1:5]};
// Iterate over the second dimension
foreach (md_array[i][j]) {
// Assign constraints for values to the second dimension
md_array[i][j] inside {[1:10]};
}
}
}
endclass
module tb;
initial begin
ABC abc = new;
abc.randomize();
$display ("md_array = %p", abc.md_array);
end
endmodule
Output
ncsim> run
md_array = '{'{'h9, 'h6, 'h7, 'h9, 'h1}, '{'h5, 'h9, 'h4, 'h2}}
ncsim: *W,RNQUIE: Simulation is complete.
The outer dimension is pinned to exactly 2 sub-arrays. Each sub-array's own size is then randomized within [1:5] — the first ends up with 5 elements, the second with 4 — and every individual value across both falls within [1:10], exactly as required.
Array Reduction Iterative Constraint
Array reduction methods can produce a single value from an array of integral values, and this can be used directly inside a constraint. Here, an array of 5 elements is constrained so their sum equals 20:
class ABC;
rand bit[3:0] array [5];
// Intrepreted as int'(array[0]) + int'(array[1]) + .. + int'(array[4]) == 20;
constraint c_sum { array.sum() with (int'(item)) == 20; }
endclass
module tb;
initial begin
ABC abc = new;
abc.randomize();
$display ("array = %p", abc.array);
end
endmodule
Output
ncsim> run
array = '{'h4, 'h2, 'h2, 'h4, 'h8}
ncsim: *W,RNQUIE: Simulation is complete.
4 + 2 + 2 + 4 + 8 = 20 — the solver found a combination of 4-bit values that sums to exactly the required total. The int'(item) cast inside the with clause avoids any width truncation surprises while accumulating the total, since each element on its own is only 4 bits wide.
Where Is This Used?
Constraining an array's sum is a common way to model something like a set of priority weights or a checksum-like field that needs to add up to a known total. Constrained multidimensional arrays are a natural fit for memory or register-file models, where the same structural rule needs to apply uniformly across every entry.
Common Beginner Mistakes
Mistake #1: Using foreach on a dynamic array or queue before its size is set
As the "Dynamic Arrays and Queues" example shows, foreach needs a known size to iterate over. Why? An unsized dynamic array or queue has to have its size fixed first — either directly (like darray = new[5] in the constructor) or through its own constraint (like queue.size() == 5) — before a foreach constraint on its elements makes sense.
Mistake #2: Nesting foreach dimensions in the wrong order for a mixed packed/unpacked array
As the multidimensional example shows, the unpacked dimensions are walked first, in declaration order, before reaching into any packed sub-dimensions. Why? Getting this order wrong means the innermost foreach variable won't actually correspond to the dimension you intended to address.
Mistake #3: Forgetting to cast array elements before using a reduction method
As the sum() example shows, casting each element with int'(item) inside the with clause avoids width-related surprises while accumulating a total. Why? Without the cast, arithmetic on narrow elements can behave unexpectedly — the cast makes sure the running total is computed with enough width to hold the actual result.
Mistake #4: Assuming foreach applies one shared random value to every element
Each element reached by a foreach constraint gets its own independently-generated value, following whatever rule the loop body expresses. Why? array[i] == i ties each element to its own index specifically — it doesn't mean every element ends up equal to each other, or to a single shared random pick.
Practice Exercise
Challenge: Constrain a Strictly Increasing Array
Write a class with rand bit [3:0] arr[5] and a foreach constraint requiring every element (after the first) to be strictly greater than the one before it.
Hint
Use foreach combined with an if (i > 0) check, comparing arr[i] against arr[i-1].
Solution
class SortedArr;
rand bit [3:0] arr[5];
constraint c_sorted {
foreach (arr[i])
if (i > 0) arr[i] > arr[i-1];
}
endclass
A result like '{2, 5, 6, 9, 13} satisfies this constraint, since each element is strictly greater than the one before it. A result like '{2, 2, 5, 9, 13} would not — the second element equals the first rather than exceeding it, violating the strict > comparison.
Summary
In this tutorial, you learned:
foreachinside a constraint applies a rule to every element of an array, with each element getting its own independently-generated value- Dynamic arrays and queues need their size established — directly or through a constraint — before
foreachcan iterate over them - Nested
foreachloops walk unpacked dimensions first, in declaration order, before reaching into any packed sub-dimensions - Array reduction methods like
sum()can be used directly inside a constraint through thewithclause, with a cast to avoid width-related truncation
SystemVerilog gives two constructs for declaring conditional relations between variables in a constraint: the implication operator, and if/else. Both express the same idea — "this rule only applies when some condition holds" — just with different syntax.
12 min read | Intermediate Level
What You'll Learn
- How the implication operator (
->) expresses "this constraint only applies when a condition holds" - Why a constrained variable is completely unconstrained — not forced to any default — whenever the antecedent condition is false
- How to write the same conditional logic using
if/elseinside a constraint block, including nested branches - Why
->alone can't express an "otherwise" branch the wayif/elsecan
Implication vs if-else: Two Equivalent Styles
// Implication operator "->" tells that len should be
// greater than 10 when mode is equal to 2
constraint c_mode { mode == 2 -> len > 10; }
// Same thing can be achieved with "if-else" construct
constraint c_mode { if (mode == 2)
len > 10;
}
mode doesn't have to equal 2 for len to be greater than 10 — the constraint only says len must be greater than 10 if mode is 2. When mode isn't 2, len is left completely unconstrained by this rule.
Example
class ABC;
rand bit [2:0] mode;
rand bit [3:0] len;
constraint c_mode { mode == 2 -> len > 10; }
endclass
module tb;
initial begin
ABC abc = new;
for(int i = 0; i < 10; i++) begin
abc.randomize();
$display ("mode=%0d len=%0d", abc.mode, abc.len);
end
end
endmodule
The results show mode doesn't need to be 2 for len to come out greater than 10:
ncsim> run mode=1 len=11 mode=6 len=3 mode=3 len=9 mode=7 len=11 mode=3 len=15 mode=2 len=12 mode=3 len=6 mode=2 len=12 mode=4 len=9 mode=7 len=13 ncsim: *W,RNQUIE: Simulation is complete.
The two rows where mode actually equals 2 both correctly show len > 10 (12 in both cases). Every other row has mode at some other value, and len is free to be anything — including values under 10, since nothing constrains it in that case.
Quick Check
Q: If mode randomizes to 5, what values can len take?
Show Answer
Any legal value in its full range, 0 through 15. Since the antecedent mode == 2 is false, c_mode imposes no requirement on len at all — it isn't forced toward any particular value, just left free.
Implication Operator
The implication operator -> shows a conditional relationship between two variables in a constraint expression. If the expression on the left-hand side is true, the expression on the right-hand side must be satisfied. If the left-hand side is false, the right-hand side isn't considered at all.
Example
class ABC;
rand bit [3:0] mode;
rand bit mod_en;
// If 5 <= mode <= 11, mod_en should be 1
constraint c_mode { mode inside {[4'h5:4'hB]} -> mod_en == 1; }
endclass
module tb;
initial begin
ABC abc = new;
for (int i = 0; i < 10; i++) begin
abc.randomize();
$display ("mode=0x%0h mod_en=0x%0h", abc.mode, abc.mod_en);
end
end
endmodule
mod_en is 1 whenever mode falls between 4'h5 and 4'hB. When that left-hand condition is false, mod_en can randomize to any value:
ncsim> run mode=0xf mod_en=0x1 mode=0x9 mod_en=0x1 mode=0x3 mod_en=0x1 mode=0xe mod_en=0x1 mode=0x1 mod_en=0x1 mode=0x0 mod_en=0x0 mode=0x1 mod_en=0x0 mode=0xe mod_en=0x0 mode=0x5 mod_en=0x1 mode=0x0 mod_en=0x0 ncsim: *W,RNQUIE: Simulation is complete.
The two rows where mode genuinely falls in [5:11] (0x9 and 0x5) both show mod_en=1, exactly as required. Everywhere else, mod_en shows up as both 0 and 1 freely, confirming it's truly unconstrained outside that range.
Quick Check
Q: Could this constraint alone ever produce mode=0x7 and mod_en=0 together?
Show Answer
No. 0x7 falls inside [5:11], so the implication requires mod_en == 1 whenever mode lands there — mod_en=0 would violate the constraint in that specific case.
if-else Constraint
The if/else constraint adds an option the plain implication operator doesn't have on its own: an explicit else branch. If the conditional expression is true, every constraint in the first set must be satisfied; otherwise, every constraint in the optional else part must be satisfied instead.
Nested if/else blocks are allowed, and multiple constraint statements within one branch need to be enclosed in curly braces { } — similar to how begin/end groups multiple statements in a procedural block like initial or always. Constraints are declarative code, though, so they use curly braces instead.
Example
The first if checks whether mode falls between 5 and 11. If true, mod_en is constrained to 1. If false, the else part runs — itself containing another if/else that checks whether mode equals 1:
class ABC;
rand bit [3:0] mode;
rand bit mod_en;
constraint c_mode {
// If 5 <= mode <= 11, then constrain mod_en to 1
// This part only has 1 statement and hence do not
// require curly braces {}
if (mode inside {[4'h5:4'hB]})
mod_en == 1;
// If the above condition is false, then do the following
else {
// If mode is constrained to be 1, then mod_en should be 1
if ( mode == 4'h1) {
mod_en == 1;
// If mode is any other value than 1 and not within
// 5:11, then mod_en should be constrained to 0
} else {
mod_en == 0;
}
}
}
endclass
module tb;
initial begin
ABC abc = new;
for (int i = 0; i < 10; i++) begin
abc.randomize();
$display ("mode=0x%0h mod_en=0x%0h", abc.mode, abc.mod_en);
end
end
endmodule
Output
ncsim> run mode=0xb mod_en=0x1 mode=0x1 mod_en=0x1 mode=0x6 mod_en=0x1 mode=0x7 mod_en=0x1 mode=0x2 mod_en=0x0 mode=0x2 mod_en=0x0 mode=0x2 mod_en=0x0 mode=0x9 mod_en=0x1 mode=0x7 mod_en=0x1 mode=0x8 mod_en=0x1 ncsim: *W,RNQUIE: Simulation is complete.
Every row matches the three-way branch exactly: mode in [5:11] (0xb, 0x6, 0x7, 0x9, 0x8) always shows mod_en=1; mode == 1 also shows mod_en=1; and mode=0x2 — matching neither of the first two conditions — consistently falls through to mod_en=0.
Where Is This Used?
Implication constraints are the standard way to express protocol legality rules like "if this is a WRITE transaction, data must be provided; if it's a READ, the data field is unused" — exactly the kind of conditional rule real bus protocols are full of, and a natural fit for a single implication or if-else constraint rather than separate transaction subclasses.
Common Beginner Mistakes
Mistake #1: Assuming the constrained variable gets some default when the antecedent is false
As both implication examples show, the variable isn't forced to any particular value — it's simply left unconstrained by that specific rule. Why? Other constraints elsewhere in the class might still apply, but this particular implication contributes nothing when its condition doesn't hold.
Mistake #2: Assuming -> alone can express an "otherwise" branch
-> only states what must hold when its left-hand side is true — it has no built-in way to require something different when it's false. Why? To actually constrain a variable differently in the false case (rather than just leave it free), if/else is the right tool, exactly as the nested example demonstrates.
Mistake #3: Forgetting curly braces around multiple statements in one branch
A single statement in an if or else branch doesn't need braces, but more than one statement does — matching the comment right in the example above. Why? Constraint blocks are declarative, and curly braces are how multiple expressions get grouped together within one conditional branch.
Mistake #4: Using = instead of == inside an if-else constraint body
Even though an if/else constraint looks a lot like procedural code, it's still a declarative expression underneath. Why? mod_en == 1; is a constraint the solver satisfies; mod_en = 1; would be an assignment, which has no meaning inside a constraint block at all.
Practice Exercise
Challenge: Constrain a Write/Read Transaction
Write a class Trans with rand bit is_write and rand bit [7:0] data. Add a constraint requiring data != 0 when is_write is 1, and data == 0 when is_write is 0.
Hint
This needs an explicit "otherwise" branch, not just a single implication — follow the same if/else pattern from this article's nested example.
Solution
class Trans;
rand bit is_write;
rand bit [7:0] data;
constraint c_data {
if (is_write)
data != 0;
else
data == 0;
}
endclass
If is_write randomizes to 0, data is forced to exactly 0. If is_write randomizes to 1, data can be any value from 1 to 255 — anything except 0. A plain implication alone couldn't express the is_write == 0 case; only the if/else form can require something specific in both branches.
Summary
In this tutorial, you learned:
- The implication operator (
->) applies a constraint only when its left-hand condition is true; otherwise the right-hand side is left entirely unconstrained - A variable left unconstrained by a false implication isn't forced to any default — it's genuinely free, subject only to whatever other constraints still apply
if/elseconstraints express the same conditional relationship, with the added ability to require something specific in the "otherwise" case, which->alone can't do- Nested
if/elseblocks are allowed, and curly braces group multiple statements within one branch, the same waybegin/endwould in procedural code
Quiz
No quiz questions available for this article.