Imagine you're writing a testbench to verify a simple design. You drive an input signal and then want to read back an output. The problem is: when exactly do you sample it? In simulation, a clock edge and your testbench code can both execute in the same time step. If your testbench reads a signal at the exact same moment the design is updating it, you can get unpredictable — or just plain wrong — values. This is called a race condition.
A clocking block solves this by acting as a timing contract between your testbench and the design. It tells the simulator: "read these signals a little before the clock edge, and drive them a little after the clock edge." This way your testbench never races with the design logic. It also lets you think in terms of transactions and cycles, rather than worrying about nanosecond-level timing every time you write stimulus.
8 min read | Intermediate Level
What You'll Learn
- Why clocking blocks exist, and the race condition they're designed to eliminate
- Why signal directions inside a clocking block are from the testbench's point of view, not the design's
- How input and output skew control exactly when a signal is sampled or driven relative to a clock edge
- What SystemVerilog does by default when no skew is specified at all
What Is a Clocking Block?
A clocking block is a named group of signals that all share the same clock. It's declared using the clocking and endclocking keywords. Once declared, any signal inside the block is sampled (read) or driven (written) relative to that clock edge, automatically applying the timing rules you set.
A few important rules to know upfront:
- A testbench can have multiple clocking blocks, and more than one of them can share the same clock event — each one still keeps its own independent skew settings, which is exactly how Part 2 of this series demonstrates several different skews on the same clock side by side
- Signal directions inside a clocking block are from the testbench's point of view, not the design's —
inputmeans the testbench is reading it (the design drives it), andoutputmeans the testbench is driving it (the design reads it) - A clocking block is most commonly declared inside an interface, so the timing rules are bundled together with the signals
Direction Convention: A Common Source of Confusion
Before looking at syntax, let's make the direction rule very clear. Suppose your design has a grant output and a request input:
- grant comes out of the design → the testbench reads it → declare as
inputin the clocking block - request goes into the design → the testbench drives it → declare as
outputin the clocking block
Think of the clocking block as sitting inside the testbench, looking at the design. What comes toward you is an input; what you send out is an output.
Basic Syntax
Here's the simplest possible clocking block — one clock, two signals, no custom skew:
clocking cb @(posedge clk);
input gnt; // testbench reads this (design drives it)
output req; // testbench drives this (design reads it)
endclocking
That's it. When the simulator hits a positive edge of clk, gnt is sampled and req can be driven, according to the default timing rules covered later in this article.
Adding Default Skew
You can tell the clocking block how far before the clock edge to sample inputs, and how far after to drive outputs. This offset is called a skew:
clocking cb @(posedge clk);
default input #1step output #2ns;
input gnt;
output req;
endclocking
default input #1step— samples all inputs in the Preponed region, just before the clock edge. This is the safest and most common choice for inputs.default output #2ns— drives all outputs 2ns after the positive edge of clk.
You can also override the skew for individual signals. In the example below, req gets its own output skew of negedge, meaning it's driven at the negative edge of the clock instead of using the default:
clocking ck1 @(posedge clk);
default input #1step output #2ns;
input gnt;
output negedge req;
endclocking
Full Syntax Reference
[default] clocking [block_name] @ [clock_event];
default input #[skew] output #[skew];
input [signal_list];
output [signal_list];
endclocking
The default keyword before clocking marks this as the default clocking block for the scope — useful when you have multiple clocking blocks and want one used by default for cycle-delay operators.
Signal Aliasing
You can also bring in a signal from elsewhere in the design hierarchy by giving it a local name inside the clocking block:
clocking ck1 @(posedge clk);
input data, valid, ready = top.dut.ready;
endclocking
Here ready = top.dut.ready creates an alias — inside this clocking block, you refer to top.dut.ready simply as ready. This is handy for signals buried deep in the hierarchy.
Declaring a Clocking Block Inside an Interface
The most practical place to put a clocking block is inside a SystemVerilog interface. This way the timing rules travel with the signals — you connect the interface to your testbench once, and everything is taken care of.
Here's a minimal but complete example. The design is a simple request-grant block: it asserts gnt one clock after it sees req:
// Design under test
module des (input logic clk, req, output logic gnt);
always @(posedge clk)
gnt <= req;
endmodule
// Interface with a clocking block
interface req_gnt_if (input logic clk);
logic req;
logic gnt;
clocking cb @(posedge clk);
default input #1step output #1ns;
input gnt; // testbench reads: comes from design
output req; // testbench drives: goes into design
endclocking
endinterface
// Testbench
module tb;
logic clk;
// Generate a 10ns clock (posedge at 5, 15, 25 ...)
initial clk = 0;
always #5 clk = ~clk;
// Instantiate the interface and the design
req_gnt_if vif (.clk(clk));
des dut (.clk(clk), .req(vif.req), .gnt(vif.gnt));
initial begin
// Drive req through the clocking block
vif.cb.req <= 0;
@(vif.cb); // wait for one clock edge
vif.cb.req <= 1; // assert request
@(vif.cb); // the DUT samples req=1 on this edge, gnt becomes 1 after it
@(vif.cb); // gnt is sampled #1step before this edge, so wait one more clock
$display("gnt = %b", vif.cb.gnt); // read grant
@(vif.cb);
vif.cb.req <= 0;
#20 $finish;
end
endmodule
Notice how the testbench drives and samples signals using vif.cb.req and vif.cb.gnt — always going through the clocking block. This ensures the timing rules are applied every time.
@(vif.cb) is how you wait for the clocking block's clock event — it's cleaner than writing @(posedge clk) directly, and keeps your testbench independent of the clock definition.
Quick Check
Q: In the testbench above, why does it write vif.cb.req instead of just vif.req?
Show Answer
Accessing a signal through the clocking block handle (vif.cb.req) applies the timing rules defined in that clocking block — in this case, driving req 1ns after the clock edge. Writing vif.req directly would bypass the clocking block entirely and reintroduce the exact race condition it exists to prevent.
Default Skew Behavior When Not Specified
If you declare a clocking block without any skew at all, the simulator applies these defaults:
- Inputs are sampled with
#1step— in the Preponed region, just before the clock edge, so they capture the stable value from the previous cycle. - Outputs with no skew (or explicit
#0) are driven in the Re-NBA region of the same time step as the clock edge. This is a special simulation scheduling region that runs after all the design's non-blocking assignments have settled, preventing the testbench from interfering with the design's own updates. It isn't the same as literally "zero nanoseconds of delay" — it's a guaranteed ordering point in the simulation scheduler.
The Preponed and Re-NBA regions are part of SystemVerilog's stratified event scheduling model — they exist specifically so that testbench-side sampling and driving never race against the design's own combinational and sequential updates in the same time step, even with no explicit skew written anywhere.
Where Are Clocking Blocks Used?
Clocking blocks are standard practice anywhere a testbench needs to reliably sample or drive DUT signals on a clock edge — protocol driver and monitor classes almost always access interface signals exclusively through a clocking block, so the same timing-safe behavior is guaranteed no matter which component or which test is using the interface.
Common Beginner Mistakes
Mistake #1: Getting the direction backwards
A signal the design drives (like gnt) is an input in the clocking block, not an output. Why? Clocking block directions are always from the testbench's point of view — it's easy to instinctively match the direction to how the signal is labeled at the DUT's own port instead, which is exactly backwards.
Mistake #2: Accessing DUT signals directly instead of through the clocking block
Writing vif.req or reading vif.gnt directly, bypassing vif.cb, works syntactically but throws away every timing guarantee the clocking block provides. Why? This reintroduces the very race condition clocking blocks exist to solve — always drive and sample through the clocking block handle once one is declared.
Mistake #3: Assuming #1step samples the current cycle's value
The default input skew, #1step, samples in the Preponed region — effectively the stable value left over from the previous time step, before anything in the current cycle has changed. Why? It's easy to assume this means "sample right at the edge," but it specifically means "sample the value as it stood just before this edge," which is what makes it race-free in the first place.
Practice Exercise
Challenge: Calculate the Drive Time
A design has a 20ns clock period. Your interface declares output #3ns req in the clocking block. If the positive clock edge occurs at simulation time 100ns, at what simulation time will req actually be driven after your testbench executes vif.cb.req <= 1?
Hint
Output skew is always measured as a delay after the clocking event it's attached to — add the skew value directly to the clock edge time.
Solution
103ns. The output skew of #3ns means the drive happens 3ns after the clocking event, and the clocking event (the positive clock edge) occurs at 100ns: 100ns + 3ns = 103ns.
Summary
In this tutorial, you learned:
- A clocking block groups signals that share a clock and gives them consistent timing rules, eliminating race conditions between testbench and design
- Signal directions are always from the testbench's point of view:
inputmeans the testbench reads it,outputmeans the testbench drives it - Input and output skew control exactly when a signal is sampled or driven relative to the clocking event, and can be set as a default or overridden per signal
- Always access signals through the clocking block handle (like
vif.cb.req) in your testbench — never drive clocking block signals directly - With no skew specified, the default input skew is
#1step(Preponed region), and the default output skew (#0) is driven in the Re-NBA region — both chosen specifically to avoid simulation race conditions
Continuing the Interfaces & Modports Chapter
Continue with SystemVerilog Clocking Blocks Part II and SystemVerilog Modport.
The conditional if else statement decides whether a statement is executed. A plain if ... else if chain says nothing about your intent. Can several conditions be true at once? Is it a mistake if none of them are? SystemVerilog lets you state that intent with three qualifiers, unique, unique0 and priority. The simulator then checks it on every evaluation, and the synthesis tool uses it to build better logic.
7 min read | Intermediate Level
What You'll Learn
- What
unique if,unique0 ifandpriority ifeach check - How to read the violation messages these checks produce in simulation
- How each qualifier changes the logic a synthesis tool builds
- When each qualifier is safe to use, and when it hides a bug
Syntax
unique if (cond1) stmt1; else if (cond2) stmt2; [else stmt3;]
unique0 if (cond1) stmt1; else if (cond2) stmt2; [else stmt3;]
priority if (cond1) stmt1; else if (cond2) stmt2; [else stmt3;]
The qualifier goes before the first if and applies to the whole if ... else if chain. Each qualifier performs different checks:
| Qualifier | Violation if more than one condition is true | Violation if no condition is true and there is no else |
|---|---|---|
unique | Yes | Yes |
unique0 | Yes | No |
priority | No | Yes |
A failed check produces a violation report. Most simulators issue it as a warning, as the *W messages in the logs below show, and the simulation keeps running.
unique-if and unique0-if
unique declares that the conditions are mutually exclusive: at most one can be true. They can therefore be evaluated in any order, or all in parallel. A unique if reports a violation when:
- more than one condition in the chain is true, or
- no condition is true and there is no final
else.
unique0 performs only the first check. It does not report a violation if none of the conditions match.
No else block for unique-if
module tb;
int x = 4;
initial begin
// This if else if construct is declared to be "unique"
// Error is not reported here because there is a "else"
// clause in the end which will be triggered when none of
// the conditions match
unique if (x == 3)
$display ("x is %0d", x);
else if (x == 5)
$display ("x is %0d", x);
else
$display ("x is neither 3 nor 5");
// When none of the conditions become true and there
// is no "else" clause, then an error is reported
unique if (x == 3)
$display ("x is %0d", x);
else if (x == 5)
$display ("x is %0d", x);
end
endmodule
ncsim> run
x is neither 3 nor 5
ncsim: *W,NOCOND: Unique if violation: Every if clause was false.
File: ./testbench.sv, line = 18, pos = 13
Scope: tb
Time: 0 FS + 1
ncsim: *W,RNQUIE: Simulation is complete.
The first chain ends in an else, so "no match" is a legal outcome and no violation is reported. The second chain has no else, so the simulator reports NOCOND: every condition was false. Had this been written as unique0 if, the second chain would have run silently.
Multiple matches in unique-if
module tb;
int x = 4;
initial begin
// This if else if construct is declared to be "unique"
// When multiple if blocks match, then error is reported
unique if (x == 4)
$display ("1. x is %0d", x);
else if (x == 4)
$display ("2. x is %0d", x);
else
$display ("x is not 4");
end
endmodule
ncsim> run
1. x is 4
ncsim: *W,MCONDE: Unique if violation: Multiple true if clauses at {line=8:pos=15 and line=10:pos=13}.
File: ./testbench.sv, line = 8, pos = 15
Scope: tb
Time: 0 FS + 1
ncsim: *W,RNQUIE: Simulation is complete.
Both conditions are true, so the overlap check fails with MCONDE, even though the chain has an else. The first matching branch is still executed. A final else only satisfies the "no match" check, never the overlap check.
Notice Time: 0 FS + 1 in the logs. The checks are deferred to the end of the time step, so a zero-delay glitch in an always_comb block, where inputs briefly overlap while settling, does not produce a false violation. Only the settled values are checked.
Quick Check
Q: A unique0 if chain has no else, and for the current inputs none of its conditions are true. Is a violation reported?
Show Answer
No. unique0 checks only for overlapping conditions. "No match" is allowed, so the chain simply does nothing.
priority-if
priority declares that the conditions must be evaluated in order and that the first true one wins, which is the normal behavior of an if ... else if chain. It also declares that at least one branch must be taken. A violation is reported only when no condition is true and there is no final else. Overlapping conditions are allowed and are not reported.
No else clause in priority-if
module tb;
int x = 4;
initial begin
// This if else if construct is declared to be "priority"
// Error is not reported here because there is a "else"
// clause in the end which will be triggered when none of
// the conditions match
priority if (x == 3)
$display ("x is %0d", x);
else if (x == 5)
$display ("x is %0d", x);
else
$display ("x is neither 3 nor 5");
// When none of the conditions become true and there
// is no "else" clause, then an error is reported
priority if (x == 3)
$display ("x is %0d", x);
else if (x == 5)
$display ("x is %0d", x);
end
endmodule
ncsim> run
x is neither 3 nor 5
ncsim: *W,NOCOND: Priority if violation: Every if clause was false.
File: ./testbench.sv, line = 18, pos = 15
Scope: tb
Time: 0 FS + 1
ncsim: *W,RNQUIE: Simulation is complete.
Exit after first match in priority-if
module tb;
int x = 4;
initial begin
// Exits if-else block once the first match is found
priority if (x == 4)
$display ("x is %0d", x);
else if (x != 5)
$display ("x is %0d", x);
end
endmodule
ncsim> run x is 4 ncsim: *W,RNQUIE: Simulation is complete.
With x = 4, both conditions are true. priority takes the first branch and reports nothing, because overlap is expected in a priority chain. The same code with unique would report MCONDE.
Using unique and priority if in Digital Design
All three qualifiers are synthesizable. They are design-intent statements as much as simulation checks.
The synthesis tool trusts the qualifier and builds simpler logic:
unique: conditions are exclusive, so the priority chain can be replaced by parallel AND-OR logic. Without anelse, the "no match" case is also treated as don't-care, so no latch is needed for it.unique0: conditions are exclusive, so parallel logic is used, but "no match" must still be handled.priority: the order is kept, and without anelsethe "no match" case is treated as don't-care.
module onehot_mux (
input logic [2:0] sel, // one-hot: at most one bit set
input logic [7:0] a, b, c,
output logic [7:0] y
);
always_comb begin
unique if (sel[0]) y = a; // tells synthesis the conditions never overlap
else if (sel[1]) y = b;
else if (sel[2]) y = c;
else y = '0; // sel == 0 is legal: drive 0
end
endmodule
Without unique, synthesis must build a priority chain in which sel[0] blocks sel[1], and so on. With it, the tool can build a flat AND-OR mux. During simulation, a MCONDE violation tells you if the one-hot assumption is ever broken.
The keyword changes the hardware, but the check runs only in simulation. If two sel bits are ever set together on silicon, the parallel mux produces a value that no branch of the RTL describes, and simulation will not match the gates. Treat every unique or priority violation in simulation as a real bug.
Where are unique and priority used?
RTL teams use unique on decoders driven by one-hot state vectors or one-hot grant signals from arbiters, where parallel logic shortens the critical path. Interrupt controllers use priority to make the order of the request checks explicit. Many verification flows promote these violations to errors so that a regression fails as soon as a design assumption breaks.
Common Beginner Mistakes
Mistake #1: Adding unique to conditions that can overlap
Wrong: unique if (addr < 16) ... else if (addr < 256) ...
Right: priority if (addr < 16) ... else if (addr < 256) ...
Why? Any addr below 16 satisfies both conditions. The code depends on order, so it is a priority chain by nature. unique would report violations, and synthesis would build the wrong logic.
Mistake #2: Thinking a final else silences all unique checks
A final else only covers the "no match" case. Why? The overlap check is separate, as the multiple-match example shows: it reported MCONDE despite having an else.
Mistake #3: Expecting priority to catch overlapping conditions
priority never reports overlap. Why? In a priority chain, overlap is normal, and the first true condition wins. If you need both the order and an overlap check, the conditions are not really prioritized. Use unique.
Practice Exercise
Challenge: Interrupt vector selection
An interrupt controller has three request lines, irq[2:0], where irq[2] has the highest priority. Several requests can be active at once. The block that computes the 2-bit vector vec is only used when at least one request is pending. Write the always_comb block and choose the right qualifier.
Hint
Requests can overlap, which rules out one qualifier. "At least one is always pending" means the no-match case should never happen, and you want simulation to tell you if it does.
Solution
always_comb begin
priority if (irq[2]) vec = 2'd2; // highest priority checked first
else if (irq[1]) vec = 2'd1;
else if (irq[0]) vec = 2'd0;
// no else: "no request" should never happen here, and
// priority reports a violation in simulation if it does
end
unique is wrong because several requests can be active together. priority keeps the order, lets synthesis treat "no request" as don't-care, and flags that case in simulation if the assumption is ever broken. Some lint tools still warn about the missing assignment in always_comb. Adding a default such as vec = '0; before the chain silences that warning, and priority still flags the no-request case.
Summary
In this tutorial, you learned:
unique ifchecks that conditions never overlap and that one always matches, unless there is anelseunique0 ifchecks only for overlap; "no match" is allowedpriority ifkeeps evaluation order and checks only that some branch is taken- Violations are deferred to the end of the time step and are usually reported as warnings
- Synthesis trusts the qualifier:
uniquegives parallel logic, and a missingelsebecomes don't-care - Every violation in simulation points to a possible simulation-versus-synthesis mismatch and should be fixed
Polymorphism allows a variable of the base class type to hold subclass objects, and to reference the methods of those subclasses directly from the superclass variable. It also allows a child class method to have a different definition than its parent class, if the parent class method is virtual.
12 min read | Intermediate Level
What You'll Learn
- Why assigning a child object to a base-class handle is allowed, and why that handle only sees the base class's own view of it
- Why the reverse assignment — base to child handle — is illegal without an explicit cast
$cast, and what happens when a downcast fails- How
virtualmethods change all of this by dispatching based on the object's actual type instead of the handle's declared type
Parent and Child Assignment
A class handle is just a container that can hold either parent or child class objects. It's important to understand how a parent class handle holding a child object — and vice versa — actually behaves.
Assign Child Class to Base Class
Taking the same example from SystemVerilog Inheritance, we'll assign a sub/child class instance sc to a base class handle bc:
module tb;
Packet bc; // bc stands for BaseClass
ExtPacket sc; // sc stands for SubClass
initial begin
sc = new (32'hfeed_feed, 32'h1234_5678);
// Assign sub-class to base-class handle
bc = sc;
bc.display ();
sc.display ();
end
endmodule
Output
ncsim> run [Base] addr=0xfeedfeed [Child] addr=0xfeedfeed data=0x12345678 ncsim: *W,RNQUIE: Simulation is complete.
Even though bc points to the child class instance, calling display() from bc still invokes the base class's own display(). This is because the function was resolved based on the type of the handle, not the type of object it's actually pointing to. Trying to reference a subclass-only member through a base class handle goes even further, producing a compile-time error:
module tb;
Packet bc; // bc stands for BaseClass
ExtPacket sc; // sc stands for SubClass
initial begin
sc = new (32'hfeed_feed, 32'h1234_5678);
bc = sc;
// Print variable in sub-class that is pointed to by
// base class handle
$display ("data=0x%0h", bc.data);
end
endmodule
Output
$display ("data=0x%0h", bc.data);
|
ncvlog: *E,NOTCLM (inheritance.sv,49|36): data is not a class item.
bc's declared type (Packet) simply has no data member, so the compiler rejects the reference entirely — regardless of what the object underneath actually contains.
Quick Check
Q: Would bc.display() behave differently if Packet's display() were declared virtual?
Show Answer
Yes. With virtual, dispatch would be based on the object's actual type instead of the handle's declared type — since bc genuinely points to an ExtPacket object, it would call ExtPacket's own display() instead of Packet's. This is exactly what the Virtual Methods section further down covers.
Assign Base Class to Child Class
It's illegal to directly assign a variable of a superclass type to a variable of one of its subclass types — this is a compile-time error:
module tb;
initial begin
bc = new (32'hface_cafe);
// Assign base class object to sub-class handle
sc = bc;
bc.display ();
end
endmodule
Output
sc = bc;
|
ncvlog: *E,TYCMPAT (inheritance.sv,56|12): assignment operator type check failed (expecting datatype compatible with 'class $unit::ExtPacket' but found 'class $unit::Packet' instead).
$cast can be used instead, to assign a superclass handle to a subclass-typed variable, provided the superclass handle actually refers to an object that's assignment-compatible with the subclass:
module tb;
initial begin
bc = new (32'hface_cafe);
// Dynamic cast base class object to sub-class type
$cast (sc, bc);
bc.display ();
end
endmodule
This compiles fine, but fails at run time, because bc here is a genuine Packet object — not an ExtPacket in disguise — so it's not actually compatible with sc's type:
ncsim> run
$cast (sc, bc);
|
ncsim: *E,BCLCST (./inheritance.sv,57|10): Invalid cast: a value with the class datatype '$unit_0x06d772f8::Packet' cannot be assigned to a class variable with the datatype '$unit_0x06d772f8::ExtPacket'.
[Base] addr=0xfacecafe
ncsim: *W,RNQUIE: Simulation is complete.
Now let's make bc point to another subclass object instead, and try the same cast again. Here, bc simply acts as a carrier for an object that's genuinely an ExtPacket underneath:
initial begin
ExtPacket sc2;
bc = new (32'hface_cafe);
sc = new (32'hfeed_feed, 32'h1234_5678);
bc = sc;
// Dynamic cast sub class object in base class handle to sub-class type
$cast (sc2, bc);
sc2.display ();
$display ("data=0x%0h", sc2.data);
end
Output
ncsim> run [Child] addr=0xfeedfeed data=0x12345678 data=0x12345678 ncsim: *W,RNQUIE: Simulation is complete.
This time the cast succeeds, and sc2 — properly typed as ExtPacket — can access data directly, no compile error involved.
Quick Check
Q: Both failed and successful $cast calls above cast from a Packet-typed handle called bc. What's actually different between them?
Show Answer
What matters for $cast is the actual object the handle points to at run time, not its declared type. In the failed case, bc points to a genuine Packet object. In the successful case, bc has been reassigned to point at the same object sc does — a real ExtPacket — so the cast has something valid to actually succeed against.
Virtual Methods
A method in the parent class can be declared virtual, which lets every child class override it with a different definition — as long as the return type and arguments (the prototype) stay the same:
class Base;
rand bit [7:0] addr;
rand bit [7:0] data;
// Parent class has a method called 'display' declared as virtual
virtual function void display(string tag="Thread1");
$display ("[Base] %s: addr=0x%0h data=0x%0h", tag, addr, data);
endfunction
endclass
class Child extends Base;
rand bit en;
// Child class redefines the method to also print 'en' variable
function void display(string tag="Thread1");
$display ("[Child] %s: addr=0x%0h data=0x%0h en=%0d", tag, addr, data, en);
endfunction
endclass
SystemVerilog Virtual Methods covers this in full depth — with virtual, calling display() through a Base-typed handle pointing at a Child object would correctly dispatch to Child's own version, solving exactly the limitation demonstrated at the top of this article.
Where Is This Used?
UVM's factory and configuration database mechanisms depend directly on this pattern — objects are stored and passed around using base-class handles like uvm_object or uvm_component, and $cast (or UVM's own wrapped equivalents) is how a specific derived type is safely recovered when the code actually needs it.
Rules to Follow
- Assignment of a derived class handle to a base class handle is allowed
- Assignment of a base class handle to a derived class handle is not allowed, and results in a compile-time error
base b = new;
child c = new;
b = c; // Allowed
c = b; // Compilation Error
$cast returns 0 if the cast failed, so use the return value to catch a failure — with if or assert:
base b = new;
child c = new;
if (! $cast(c, b))
$error("Cast failed !");
assert($cast(c, b)) else
$error("Cast failed !");
Common Beginner Mistakes
Mistake #1: Assuming a base-typed handle can reach child-only members
As the bc.data example shows, this is a compile-time error, not a run-time one. Why? The compiler only knows what the handle's declared type promises — it has no way to know, at compile time, that the actual object underneath happens to have more members.
Mistake #2: Assigning a base handle directly into a child-typed handle
sc = bc; fails to compile, full stop — there's no implicit downcast in SystemVerilog. Why? A base class object isn't guaranteed to actually be the more specific subclass type, so the language requires you to be explicit about that assumption using $cast instead.
Mistake #3: Forgetting to check $cast's return value
A failed $cast doesn't stop simulation on its own — it just returns 0 and the destination handle doesn't end up with the intended object. Why? Code that assumes the cast always succeeds can silently continue operating without the object it expected, rather than failing loudly — always check the return value with if or assert.
Mistake #4: Assuming $cast works between any two unrelated classes
$cast still requires an actual inheritance relationship between the two types involved. Why? It's for safely recovering a more specific type from a handle that's currently typed more generally within the same class hierarchy — not a way to convert between two classes that have nothing to do with each other.
Practice Exercise
Challenge: Predict a Successful and a Failed Cast
Using the Packet/ExtPacket classes from this article, write code that creates a plain Packet object and a separate ExtPacket object, assigns both to Packet-typed handles, and attempts $cast into an ExtPacket-typed handle from each one. Predict which cast succeeds and which fails.
Hint
The declared type of the intermediate Packet-typed handle doesn't matter for $cast — only the actual object each one is currently pointing to does.
Solution
module tb;
Packet bc1, bc2;
ExtPacket sc, result;
initial begin
bc1 = new (32'hface_cafe); // A plain Packet object
sc = new (32'hfeed_feed, 32'h1234_5678);
bc2 = sc; // bc2 actually points to an ExtPacket
if ($cast (result, bc1))
$display ("Cast from bc1 succeeded");
else
$display ("Cast from bc1 failed");
if ($cast (result, bc2))
$display ("Cast from bc2 succeeded");
else
$display ("Cast from bc2 failed");
end
endmodule
The cast from bc1 fails, since bc1 points to a genuine Packet object with no ExtPacket underneath it. The cast from bc2 succeeds, since bc2 was reassigned to point at the same object sc does — a real ExtPacket — exactly the same distinction demonstrated earlier in this article.
Summary
In this tutorial, you learned:
- A base class handle can hold a child class object, but without
virtual, method calls through it still resolve to the base class's own version - A base-typed handle can't access a child-only member at all — that's a compile-time error, regardless of the actual object underneath
- Assigning a base handle directly into a child-typed handle is illegal;
$castis required to attempt it explicitly $castsucceeds or fails based on the object a handle actually points to at run time, not the handle's declared type — and it returns0on failure rather than stopping simulationvirtualmethods (covered in their own article) are what let a base-typed handle correctly dispatch to a child's overridden method
Both while and do while are looping constructs that run a set of statements for as long as a condition stays true. They differ only in when the condition is checked. A while loop checks before each pass, so its body may never run. A do while loop checks after each pass, so its body always runs at least once.
6 min read | Intermediate Level
What You'll Learn
- The syntax of
whileanddo while, and how their checks differ - How to poll for a condition in a testbench without hanging the simulation
- When to choose
do whileoverwhile - Why these loops are rarely used in synthesizable RTL
Syntax
while (<condition>) begin
// Multiple statements
end
do begin
// Multiple statements
end while (<condition>);
- condition: any expression. The loop continues while it is true, meaning non-zero. If it is X or Z, it counts as false.
begin ... endis only required when the body has more than one statement.- A
do whileloop must end with a semicolon after the closing parenthesis.
A while loop checks the condition first and runs the statements only if it is true. If the condition is false, the loop ends right there. A do while loop runs the statements once first and then checks the condition. It keeps going until the condition becomes false.
Example #1: while Loop
module tb;
initial begin
int cnt = 0;
while (cnt < 5) begin
$display("cnt = %0d", cnt);
cnt++;
end
end
endmodule
ncsim> run cnt = 0 cnt = 1 cnt = 2 cnt = 3 cnt = 4 ncsim: *W,RNQUIE: Simulation is complete.
The condition is checked six times. It is true for cnt = 0 to 4 and false when cnt reaches 5, so the body runs five times.
Example #2: while Loop That Never Runs
module tb;
initial begin
int cnt;
while (cnt != 0) begin
$display ("cnt = %0d", cnt);
cnt++;
end
end
endmodule
ncsim> run ncsim: *W,RNQUIE: Simulation is complete.
cnt is an int, which is 2-state and starts at 0. The condition cnt != 0 is false on the very first check, so the body never runs and nothing is printed.
Example #3: do while Loop
module tb;
initial begin
int cnt = 0;
do begin
$display("cnt = %0d", cnt);
cnt++;
end while (cnt < 5);
end
endmodule
ncsim> run cnt = 0 cnt = 1 cnt = 2 cnt = 3 cnt = 4 ncsim: *W,RNQUIE: Simulation is complete.
When the condition is true on entry, do while gives the same result as Example #1.
Example #4: do while Runs at Least Once
module tb;
initial begin
int cnt = 0;
do begin
$display("cnt = %0d", cnt);
cnt++;
end while (cnt == 0);
end
endmodule
ncsim> run cnt = 0 ncsim: *W,RNQUIE: Simulation is complete.
The body runs once, printing 0 and incrementing cnt to 1. Only then is cnt == 0 checked. It is false, so the loop ends after a single pass.
Quick Check
Q: If Example #2 used a do while loop with the same condition cnt != 0, what would happen?
Show Answer
The body would run once and print cnt = 0, then increment cnt to 1. Now cnt != 0 is true, and since nothing ever brings cnt back to 0, the loop would run until cnt wraps around after about 4 billion passes. The condition matters as much as the choice of loop.
Using while in Verification: Polling with a Timeout
The most common testbench use of while is waiting for the DUT to do something, such as raise a ready flag, while also guarding against waiting forever.
module tb;
bit clk, ready;
int cycles = 0;
always #5 clk = ~clk; // rising edges at 5, 15, 25 ... ns
initial #42 ready = 1; // stands in for the DUT raising ready
initial begin
// Check once per clock; give up after 100 cycles
while (!ready && cycles < 100) begin
@(posedge clk); // advances time, so ready can change
cycles++;
end
if (ready) $display ("[%0t] ready after %0d cycles", $time, cycles); // [45] ready after 5 cycles
else $display ("[%0t] TIMEOUT waiting for ready", $time);
$finish;
end
endmodule
Two details make this loop safe. The @(posedge clk) lets time advance, so the process that sets ready gets to run. The cycle limit guarantees the loop ends even if the DUT is broken.
Where are while and do while used in verification?
Drivers use while to hold a transfer until the DUT accepts it, as in AXI-style valid/ready handshakes. Tests use do while for operations that must be tried at least once, such as polling a status register over a bus until a busy bit clears. You always have to read the register once before you know whether to read it again.
while and do while in Digital Design
Synthesis tools can unroll a loop only when they can work out the number of passes at elaboration time. A while loop whose condition depends on signal values does not meet that rule and will not synthesize. Some tools accept a while loop with constant start, step and limit values, but a for loop expresses the same thing more clearly and is supported everywhere. In RTL, use for and keep while and do while for testbenches.
Common Beginner Mistakes
Mistake #1: A semicolon right after while (condition)
Wrong: while (cnt < 5); begin cnt++; end
Right: while (cnt < 5) begin cnt++; end
Why? The semicolon is an empty statement, so it becomes the whole loop body. cnt never changes, the loop never ends, and the begin ... end block is never reached.
Mistake #2: Forgetting the semicolon at the end of do while
Wrong: do begin ... end while (cnt < 5)
Right: do begin ... end while (cnt < 5);
Why? In a do while loop, the while (...) clause ends the statement and needs its own semicolon. Leaving it out is a syntax error, and compilers often report it on the line that follows.
Mistake #3: Polling a signal without letting time advance
Wrong: while (!ready) cycles++;
Right: while (!ready) @(posedge clk);
Why? ready is driven by another process, which can only run when this one waits. Without an event or delay in the body, the loop spins at the same timestamp forever.
Practice Exercise
Challenge: Pick a random address until it is aligned
Using $urandom_range(0, 63), pick a random address until you get one that is a multiple of 4. Print the address and how many tries it took. Which loop fits best, and why?
Hint
You cannot test an address before you have generated one, so the body must run at least once.
Solution
module tb;
int unsigned addr;
int tries;
initial begin
do begin
addr = $urandom_range(0, 63); // pick a candidate
tries++;
end while (addr % 4 != 0); // try again until 4-byte aligned
$display ("addr = %0d after %0d tries", addr, tries);
end
endmodule
do while fits because the address must be generated before it can be checked. With while, you would need an extra assignment before the loop. In a class-based testbench, a constraint such as addr % 4 == 0 does the same job more efficiently.
Summary
In this tutorial, you learned:
whilechecks its condition before each pass and may run its body zero timesdo whilechecks after each pass and always runs its body at least once- A
do whileloop must end with a semicolon afterwhile (condition) - When polling a signal, the body needs a timing control, and a cycle limit protects against hangs
- In RTL, a
forloop with constant bounds is preferred overwhile
SystemVerilog functions and tasks share the same core characteristics as their Verilog counterparts, with a set of enhancements layered on top: ANSI-style declarations, default argument values, named-argument calls, and reference passing all work the same way for both. The one rule that never changes is that a function can't consume simulation time and can't call a task — no @, #, fork...join, or wait statements are allowed inside one — which is exactly the gap a task exists to fill. See Verilog Functions and Verilog Task for a refresher on the basics shared between the two languages.
14 min read | Intermediate Level
What You'll Learn
- The two restrictions every function has to follow: no time controls, and no calling a task
- How ANSI-C style declarations work, and the implicit same-named return variable every function gets
- How old-style
input/outputport declarations interact with that same implicit return variable - How to give an argument a default value, and call with some arguments named instead of positional
- The difference between passing arguments by value and by reference
- Why a subroutine with
staticlifetime can't accept arefargument - How
const refcombines the efficiency of reference passing with a compiler-enforced guarantee against modification - What makes a task different from a function — and why that's the one restriction a function can't get around
ANSI-C Style Declaration
A function can be called and used in two ways: assign its return value to a variable first, or use the returned value directly inside an expression. Every function also gets an implicit variable with the same name as the function itself, which can be assigned directly as an alternative to using return:
module tb;
// There are two ways to call the function:
initial begin
// 1. Call function and assign value to a variable, and then use variable
int s = sum(3, 4);
$display ("sum(3,4) = %0d", s);
// 2. Call function and directly use value returned
$display ("sum(5,9) = %0d", sum(5,9));
$display ("mul(3,1) = %0d", mul(3,1));
end
// This function returns value of type "byte", and accepts two
// arguments "x" and "y". A return variable of the same name as
// function is implicitly declared and hence "sum" can be directly
// assigned without having to declare a separate return variable
function byte sum (int x, int y);
sum = x + y;
endfunction
// Instead of assigning to "mul", the computed value can be returned
// using "return" keyword
function byte mul (int x, y);
return x * y;
endfunction
endmodule
Output
ncsim> run sum(3,4) = 7 sum(5,9) = 14 mul(3,1) = 3 ncsim: *W,RNQUIE: Simulation is complete.
sum assigns its own implicit return variable directly (sum = x + y;), while mul uses return x * y; instead — both are valid, equivalent ways to set what the function returns.
Quick Check
Q: If mul's body were changed from return x * y; to mul = x * y;, would mul(3,1) still return 3?
Show Answer
Yes. mul is the function's own implicit return variable, so assigning to it directly has exactly the same effect as using return — they're two different ways of doing the same thing.
Using Old-Style Declarations and Directions
The older, pre-ANSI-C style of declaring port directions is still valid in SystemVerilog. A function can accept input and output ports, in addition to (or instead of) using its own implicit return variable:
module tb;
initial begin
int res, s;
s = sum(5,9);
$display ("s = %0d", sum(5,9));
$display ("sum(5,9) = %0d", sum(5,9));
$display ("mul(3,1) = %0d", mul(3,1,res));
$display ("res = %0d", res);
end
// Function has an 8-bit return value and accepts two inputs
// and returns the result through its implicit return variable "sum"
function bit [7:0] sum;
input int x, y;
sum = x + y;
endfunction
// Same as above but ports are given inline
function byte mul (input int x, y, output int res);
res = x*y + 1;
return x * y;
endfunction
endmodule
Output
ncsim> run s = 14 sum(5,9) = 14 mul(3,1) = 3 res = 4 ncsim: *W,RNQUIE: Simulation is complete.
mul here is the interesting one: it both returns a value and writes to an explicit output port, and the two don't have to agree. res = x*y + 1 = 4 is written to the caller's res variable through the output port, while return x*y = 3 is a completely separate value handed back through the function's normal return mechanism. The call site's $display("mul(3,1) = %0d", mul(3,1,res)) uses the return value (3), while the later $display("res = %0d", res) reads whatever the output port actually wrote (4) — two independent channels out of the same function call.
sum has only two ports, x and y, and hands its result back through the implicit same-named return variable. It can't also declare an output port called sum: a function isn't allowed to declare another object with its own name, so the result has to come back through that implicit variable.
Quick Check
Q: In the mul example, if the call site only ever displayed res and never called $display("mul(3,1) = %0d", mul(3,1,res)), would res still end up as 4?
Show Answer
Yes. res is populated by the output port assignment (res = x*y + 1;) every time the function is called, completely independently of whether anything ever reads or displays the function's separate return value.
Default Argument Values
An ANSI-style argument can specify a default value with = expression. If the caller omits that argument — or leaves its position empty in a positional call — the compiler supplies the default instead:
module tb;
initial begin
int r1, r2, r3;
r1 = scale(5); // b uses its default of 10
r2 = scale(5, 3); // b explicitly overridden to 3
r3 = scale( , 3); // a uses its default of 1, b overridden to 3
$display("r1 = %0d r2 = %0d r3 = %0d", r1, r2, r3);
end
// "a" defaults to 1, "b" defaults to 10
function int scale(int a = 1, int b = 10);
return a * b;
endfunction
endmodule
Output
r1 = 50 r2 = 15 r3 = 3
Defaults only work with ANSI-style declarations, and a default expression is only evaluated on calls that actually use it — it's re-evaluated fresh each time, not computed once and cached.
Leaving an earlier argument empty, as in scale( , 3), is only legal if that argument has a default of its own. An argument with no default can never be skipped, whether by position or by leaving it blank. Defaults don't have to be trailing either — an argument with no default is allowed to sit between two arguments that do have defaults.
Calling with Named Arguments
Arguments can also be bound by name instead of position, using .argument_name(expression) at the call site. This makes it easy to override just one default out of several, in any order:
module tb;
initial begin
$display("scale(.b(3)) = %0d", scale(.b(3))); // a defaults to 1
$display("scale(.b(3), .a(5)) = %0d", scale(.b(3), .a(5))); // named args, any order
$display("scale(5, .b(3)) = %0d", scale(5, .b(3))); // positional then named
end
function int scale(int a = 1, int b = 10);
return a * b;
endfunction
endmodule
Output
scale(.b(3)) = 3 scale(.b(3), .a(5)) = 15 scale(5, .b(3)) = 15
Named arguments can appear in any order relative to each other, which is what makes scale(.b(3), .a(5)) and a hypothetical scale(.a(5), .b(3)) equivalent.
Positional and named arguments can be mixed in the same call, but every positional argument has to come before any named one. scale(5, .b(3)) is legal; writing the named argument first, as in scale(.b(3), 5), is a compile error.
Passing Arguments by Value
Pass by value is the default way arguments reach a subroutine. Each argument is copied into the subroutine's own local storage, and changes made to that local copy never propagate back to the caller:
module tb;
initial begin
int a, res;
// 1. Lets pick a random value from 1 to 10 and assign to "a"
a = $urandom_range(1, 10);
$display ("Before calling fn: a=%0d res=%0d", a, res);
// Function is called with "pass by value" which is the default mode
res = fn(a);
// Even if value of a is changed inside the function, it is not reflected here
$display ("After calling fn: a=%0d res=%0d", a, res);
end
// This function accepts arguments in "pass by value" mode
// and hence copies whatever arguments it gets into this local
// variable called "a".
function int fn(int a);
// Any change to this local variable is not
// reflected in the main variable declared above within the
// initial block
a = a + 5;
// Return some computed value
return a * 10;
endfunction
endmodule
Output
ncsim> run Before calling fn: a=2 res=0 After calling fn: a=2 res=70 ncsim: *W,RNQUIE: Simulation is complete.
The exact starting value shown here (2) depends on the simulation's random seed, since it comes from $urandom_range(1,10) — a different run could show a different number. What matters, and what will always hold regardless of seed, is that the caller's a stays completely unchanged after the call (still whatever it was before), even though the function's own local a was modified (a + 5) on the way to computing the return value.
Passing Arguments by Reference
A ref argument isn't copied — the subroutine gets a direct reference to the caller's own variable, so changes made inside are visible outside once the call returns. Reusing the exact same calling code as the pass-by-value example above, only the function itself changes:
// Use "ref" to make this function accept arguments by reference
// Also make the function automatic
function automatic int fn(ref int a);
// Any change to this local variable will be
// reflected in the main variable declared within the
// initial block
a = a + 5;
// Return some computed value
return a * 10;
endfunction
fn here must be declared automatic — it's illegal to pass an argument by reference to a subroutine with static lifetime, since a static subroutine's storage is meant to persist and be shared across every call, while a ref argument is tied to one specific caller's variable that only makes sense for that one call.
Output
ncsim> run Before calling fn: a=2 res=0 After calling fn: a=7 res=70 ncsim: *W,RNQUIE: Simulation is complete.
This time, a genuinely changes to 7 after the call — the exact same a = a + 5; line as the pass-by-value version, but now operating directly on the caller's own storage instead of a disposable local copy. res still comes out to 70, since the underlying calculation ((a+5) * 10) is identical either way — the only difference between the two examples is whether the caller's own a persists the change afterward.
Quick Check
Q: If the pass-by-value example's starting a had been 5 instead of 2, what would a and res show after the call, using the reference version of fn?
Show Answer
a = 10, res = 100. With ref, the caller's a is updated to 5 + 5 = 10 by the function, and res receives the return value 10 * 10 = 100.
Where Are Functions Used?
Functions are the right choice for anything that computes a value from its inputs instantly, with no waiting involved — calculating a checksum or CRC over a data packet, converting between data representations, or any small utility calculation a class needs. The moment something needs to wait for a clock edge or an event, it belongs in a task instead, since a function simply isn't allowed to consume time.
const ref: Reference Efficiency Without the Mutability Risk
Passing by reference avoids copying large data — genuinely valuable for a big array or a large struct, where copying on every call would be wasteful. But it also means the function can modify the caller's original data, whether that was actually intended or not. const ref gives you the efficiency of reference passing while removing that risk entirely: the argument still isn't copied, but the compiler refuses to let the function body write to it at all.
function automatic int sum_it (const ref int a []);
int total = 0;
foreach (a[i])
total += a[i];
// a[0] = 99; // Illegal: 'a' is const, this is a compile-time error
return total;
endfunction
module tb;
initial begin
int data[] = '{1, 2, 3, 4, 5};
$display ("sum = %0d", sum_it(data));
end
endmodule
This prints sum = 15. data is never copied into sum_it — it's accessed directly through the reference, exactly as efficient as a plain ref argument would be. But unlike plain ref, attempting a[0] = 99; inside the function body is rejected at compile time, not just discouraged by convention. const ref still requires the function to be automatic, for the same reason plain ref does — it's still fundamentally a reference-passing mode.
Quick Check
Q: If sum_it's argument were changed from const ref int a [] to plain ref int a [], would the function still work correctly?
Show Answer
Yes — sum_it never actually modifies a, so removing const wouldn't break anything at runtime. But it would silently remove the compiler's guarantee that it never will, even after a future edit — const ref documents and enforces that guarantee, plain ref doesn't.
Tasks
A task shares the same declaration syntax as a function — ANSI-style or old-style ports, default argument values, named-argument calls, pass by value, reference, or const ref — all of it works identically. What's different is what a task is allowed to do, and what it hands back to its caller.
Tasks Can Consume Time
Unlike a function, a task can contain @, #, wait, and fork...join statements, and it can call other tasks as well as functions. This is the one capability that decides whether something has to be a task rather than a function: anything that needs to wait belongs in a task.
module tb;
logic clk = 0;
always #5 clk = ~clk; // 10ns period clock
logic [7:0] bus = 8'hA5;
// Waits for "cycles" clock edges, then samples bus through an output port
task automatic wait_cycles_and_read(input int cycles, output logic [7:0] data);
repeat (cycles) @(posedge clk);
data = bus;
endtask
initial begin
logic [7:0] captured;
$display("t=%0t : calling task", $time);
wait_cycles_and_read(3, captured);
$display("t=%0t : captured = 0x%0h", $time, captured);
end
endmodule
Output
t=0 : calling task t=25 : captured = 0xa5
The call to wait_cycles_and_read doesn't return until three clock edges have actually happened in simulation — at t=5, t=15, and t=25 — which a function could never do.
No Return Value, No Implicit Same-Named Variable
A task has no return value at all, so it gets none of the implicit same-named variable a function gets. A bare return; with no expression is still legal inside a task, to exit early, but return some_value; is a compile error.
Since a task can't hand back a result through a return value, output and inout ports are the normal way a task communicates results to its caller — exactly how data works in wait_cycles_and_read above. A task can also declare several output ports at once, something a function's single return value can't do on its own.
Forking additional processes inside a task with fork...join_none or join_any can let the task return to its caller while those forked processes keep running in the background. See SystemVerilog fork join for how each join variant behaves.
Unlike a plain (non-void) function, a task's call can drop the parentheses entirely when no arguments need to be supplied — either because the task takes none, or because every argument has a default and the call wants to use them all. A plain function always needs at least an empty (), defaults or not.
Quick Check
Q: If wait_cycles_and_read were rewritten as a function instead of a task, keeping the exact same body, would it still compile?
Show Answer
No. The repeat (cycles) @(posedge clk); line consumes simulation time, which is illegal inside a function. Anything that needs to wait for an event has to be a task.
Common Beginner Mistakes
Mistake #1: Trying to consume time inside a function
Any @, #, wait, or fork...join statement inside a function is a compile error, and a function can't call a task either. Why? A function is meant to compute and return a value immediately, within the same simulation time step it was called — if what you need genuinely requires waiting, that's exactly what a task is for.
Mistake #2: Assuming a function's return value and an output port can't disagree
As the mul example shows, a function's own return value and an explicit output port argument are two independent channels — there's no rule that they have to compute the same result. Why? It's easy to assume they're automatically linked just because they come from the same function call, but each is set by its own separate assignment inside the function body.
Mistake #3: Passing a ref argument to a static subroutine
This is explicitly illegal. Why? A static subroutine's storage is shared across every call to it, while a ref argument is inherently tied to one specific caller's variable for one specific call — the two lifetimes are fundamentally incompatible, so the subroutine accepting a ref argument has to be automatic.
Mistake #4: Using plain ref when the function never needs to modify the argument
As the sum_it example shows, a large array only needs to be read, not written — yet plain ref still leaves the door open for a future edit to accidentally modify the caller's data. Why? const ref costs nothing extra in performance and makes the "read-only" intent a compiler-enforced guarantee instead of just a convention someone has to remember to follow.
Mistake #5: Putting a named argument before a positional one
scale(.b(3), 5) is a compile error — if both positional and named arguments appear in the same call, every positional argument has to come first.
Reorder the call so any named arguments come last, or just use named arguments for every argument in that call.
Mistake #6: Trying to return a value from a task
return some_value; inside a task is a compile error, since a task has no return value and no implicit same-named variable the way a function does.
Use a bare return; to exit a task early, and an output or inout port to hand back an actual result.
Practice Exercise
Challenge: Predict Two Independent Results
Given function byte combine (input int x, y, output int total); total = x + y; return x - y; endfunction, called as combine(10, 3, total), what does the call itself return, and what does total hold afterward?
Hint
Work out the output port's assignment and the return statement completely separately — they use different expressions and don't have to match.
Solution
The call returns 7 (return x - y = 10 - 3), and total ends up as 13 (total = x + y = 10 + 3) — two different numbers from the exact same call, exactly like mul's 3 and 4 earlier in this article.
Challenge: A Task With a Default Argument
Write a task pulse that drives a ref argument sig high, waits for a default of 2 clock edges (an input int cycles = 2 argument), then drives sig back low. Call it once using the default, and once overriding cycles to 5 with a named argument.
Hint
Combine what you already know about default argument values with repeat (cycles) @(posedge clk);, exactly like wait_cycles_and_read earlier in this article.
Solution
module tb;
logic clk = 0;
always #5 clk = ~clk;
logic sig;
task automatic pulse(ref logic sig, input int cycles = 2);
sig = 1;
repeat (cycles) @(posedge clk);
sig = 0;
endtask
initial begin
pulse(sig); // uses the default: 2 cycles
pulse(sig, .cycles(5)); // named argument overrides the default
end
endmodule
Because sig is passed by ref, the caller sees each change immediately (an output argument would only be copied back when the task returns). The first call holds sig high for 2 clock edges using the default, and the second holds it high for 5 using a named override — the same default-argument mechanics as scale earlier in this article, just applied to a task instead of a function.
Summary
In this tutorial, you learned:
- A function can't consume simulation time and can't call a task — it computes and returns a value immediately
- Every function has an implicit return variable sharing its own name, which can be assigned directly as an alternative to
return - Old-style
input/outputport declarations are still valid, and a function's return value and anyoutputport are independent, separately-assigned channels - An ANSI-style argument can specify a default value with
= expression, and a call can skip it by position (leaving that slot empty) or by name - Arguments can be bound by name with
.argument(expression)at the call site, in any order relative to each other — but positional arguments must come before named ones in the same call - Pass by value (the default) copies an argument in; changes inside the subroutine never affect the caller's original variable
- Pass by reference (
ref) shares the caller's actual variable directly, so changes inside are visible outside — but this requires the subroutine to beautomatic, neverstatic const refcombines reference-passing efficiency (no copy) with a compile-time guarantee that the argument can never be modified — the right default whenever a large argument only needs to be read- A task can consume simulation time and call other tasks or functions, unlike a function — but it has no return value and no implicit same-named variable, so results go through
output/inoutports instead
Continuing the Advanced Features Chapter
Continue with SystemVerilog Package.
Quiz
No quiz questions available for this article.