4-state values — 0, 1, unknown (X), and high-impedance (Z) — were already covered in detail in the Verilog tutorial on Verilog Data Types. This article is a quick refresher on that, before focusing on what SystemVerilog adds to the picture: the logic keyword.
Every signal in a design is really two things layered together: an object kind — whether it's a variable or a net — and a data type, the set of values it can hold (like logic, bit, or int). logic itself is just a data type, not an object on its own; SystemVerilog's real improvement is letting that one data type be used for either object kind, which is what this article focuses on.
7 min read | Beginner Level
What You'll Learn
- A quick refresher on 4-state values, with a link to the full explanation
- Why
logicis a data type, not a variable or a net by itself - How to drive
logicfrom a procedural block only, and from a continuous assign only - How
wire logicdiffers from a plainlogicdeclaration
Quick Refresher: 4-State Values
A 4-state data type can hold 0, 1, X (unknown), or Z (high-impedance). Every net (wire) and variable (reg) in Verilog uses 4-state values, but they don't share a default: an undriven net defaults to Z (nothing is driving it), while an undriven variable defaults to X (unknown, uninitialized) — neither ever defaults to 0.
For the full breakdown of what X and Z represent in real hardware, and how nets differ from variables, see Verilog Data Types.
Quick Check
Q: What's the default value of an undriven wire, versus an undriven logic or reg?
Show Answer
A wire is a net, so with nothing driving it, it defaults to Z (high-impedance). logic and reg default to X (unknown) instead, since a plain declaration of either implicitly makes it a variable. Neither ever defaults to 0. See Verilog Data Types for why this matters for catching reset and initialization bugs.
logic: A 4-State Data Type
logic is a 4-state data type — its value set (0, 1, X, Z) is identical to reg's. It isn't, by itself, a variable or a net; it's just the type. When you write a plain declaration like logic a; with no other keyword, SystemVerilog implicitly treats that as var logic a; — a variable of type logic.
That's why a plain logic signal behaves like the classic reg by default: driven from a procedural block, or from a single continuous assign, but never from more than one driver, and never from both a continuous assign and a procedural block on the same signal at once. That single-driver restriction belongs to variables in general, not to the logic type specifically.
In standard Verilog, a reg could only ever be assigned inside a procedural block (always, initial) — driving a reg with a continuous assign statement was a syntax error. SystemVerilog changed this: reg and logic are now identical 4-state variable types, and SystemVerilog relaxed the strict Verilog distinction between nets and variables, allowing a continuous assign to drive a variable of either keyword. In practice almost everyone reaches for logic to take advantage of this, but the rule itself applies equally to reg.
The part that's genuinely new is that logic can also be used to declare a net, by pairing it with a net keyword: wire logic w;. A net of type logic behaves like any other net — it can legally have multiple drivers, resolved by strength.
In fact, plain wire is really shorthand for a net with this same 4-state value set, so wire and wire logic behave identically; the explicit form is rarely written out, but it's what's happening underneath.
Syntax
logic [msb:lsb] signal_name; // implicit variable -- same as: var logic signal_name;
var logic [msb:lsb] signal_name; // explicit variable, identical to the line above
wire logic [msb:lsb] signal_name; // net of type logic -- supports multiple drivers
The comparison above reflects the conventional, most-common usage of each keyword: reg is almost always written as a purely procedural variable (its classic Verilog role), and wire is almost always a net. Technically, since reg and logic are the same underlying type in SystemVerilog, a plain reg variable can also legally take a single continuous assign — it's just rarely written that way, since logic is the modern convention for exactly that case. Pairing either keyword-equivalent type with wire instead (wire logic) produces a net, which supports multiple drivers just like any other net.
Quick Check
Q: Can a logic signal be driven by two separate continuous assign statements at the same time?
Show Answer
Not if it's declared the usual way (logic a;), since that implicitly makes it a variable, and variables support only one driver total. But wire logic a; declares a net of type logic instead, and nets are explicitly built to support multiple drivers, resolved by strength.
Example 1: Driven from Both a Procedural Block and a Continuous Assign
module tb;
logic [3:0] my_data; // Declare a 4-bit logic type variable
logic en; // Declare a 1-bit logic type variable
initial begin
$display ("my_data=0x%0h en=%0b", my_data, en); // Default value of logic type is X
my_data = 4'hB; // logic datatype can be driven in initial/always blocks
$display ("my_data=0x%0h en=%0b", my_data, en);
#1;
$display ("my_data=0x%0h en=%0b", my_data, en);
end
assign en = my_data[0]; // logic datatype can also be driven via assign statements
endmodule
Output
ncsim> run my_data=0xx en=x my_data=0xb en=x my_data=0xb en=1 ncsim: *W,RNQUIE: Simulation is complete.
Right after my_data = 4'hB;, en still prints as x, even though it's continuously driven by assign en = my_data[0];. The continuous assign does react to the change, but as a separate event in the same simulation time step, with no guarantee it completes before the next $display runs. Only after #1; advances time does en correctly show 1.
my_data and en are two separate logic variables here — one driven procedurally, the other by a continuous assign. A single variable can only ever have one of these, never both: mixing a continuous assign and a procedural block on the same variable is illegal, and so is giving one variable two continuous assigns. See Common Mistakes below for what that looks like and how to fix it.
Example 2: Driven Purely from a Procedural Block
my_data above was still only ever assigned procedurally; here's a logic signal driven entirely inside an always_comb block, with no continuous assign involved at all — a 4-to-1 mux.
module tb;
logic [1:0] sel;
logic [7:0] a, b, c, d;
logic [7:0] mux_out;
// mux_out is driven only from inside this procedural block
always_comb begin
case (sel)
2'b00: mux_out = a;
2'b01: mux_out = b;
2'b10: mux_out = c;
2'b11: mux_out = d;
endcase
end
initial begin
a = 8'h11; b = 8'h22; c = 8'h33; d = 8'h44;
sel = 2'b00; #1;
$display ("sel=%0b mux_out=0x%0h", sel, mux_out);
sel = 2'b10; #1;
$display ("sel=%0b mux_out=0x%0h", sel, mux_out);
sel = 2'b11; #1;
$display ("sel=%0b mux_out=0x%0h", sel, mux_out);
end
endmodule
Output
sel=00 mux_out=0x11 sel=10 mux_out=0x33 sel=11 mux_out=0x44
always_comb automatically re-evaluates whenever any signal it reads — sel, a, b, c, or d — changes, so mux_out always reflects the currently selected input. Just like the previous example, the #1 after each sel change gives the block time to settle before the value is displayed.
This is the pattern you'll see in almost every combinational RTL block written in modern SystemVerilog: logic outputs assigned entirely inside an always_comb, with no wire or assign in sight.
Example 3: Driven Purely from a Continuous Assign
logic can just as easily be driven the old wire-style way, with no procedural block at all.
module tb;
logic a, b;
logic y_and, y_or, y_xor;
// All three outputs are driven only by continuous assigns
assign y_and = a & b;
assign y_or = a | b;
assign y_xor = a ^ b;
initial begin
a = 1'b0; b = 1'b0; #1;
$display ("a=%0b b=%0b and=%0b or=%0b xor=%0b", a, b, y_and, y_or, y_xor);
a = 1'b1; b = 1'b0; #1;
$display ("a=%0b b=%0b and=%0b or=%0b xor=%0b", a, b, y_and, y_or, y_xor);
a = 1'b1; b = 1'b1; #1;
$display ("a=%0b b=%0b and=%0b or=%0b xor=%0b", a, b, y_and, y_or, y_xor);
end
endmodule
Output
a=0 b=0 and=0 or=0 xor=0 a=1 b=0 and=0 or=1 xor=1 a=1 b=1 and=1 or=1 xor=0
Nothing here is different from how you'd write this with wire — logic accepts continuous assigns exactly the same way. The only thing that changes is the keyword in the declaration.
In practice, most SystemVerilog style guides now recommend declaring every internal signal as logic by default, and only reaching for wire the moment a signal actually needs more than one driver — for example, a shared bus.
What It Synthesizes Into
Declaring a signal as logic says nothing about whether it becomes a wire, a gate output or a flip-flop. That is decided by how the signal is assigned. In the module below every signal is a logic.
module logic_kinds (
input logic clk,
input logic [7:0] a, b,
output logic [7:0] sum_q, larger, a_inv
);
logic [7:0] sum;
always_comb sum = a + b; // an 8-bit adder
always_ff @(posedge clk)
sum_q <= sum; // 8 flip-flops
assign larger = (a > b) ? a : b; // a comparator and a mux
assign a_inv = ~a; // 8 inverters
endmodule
Synthesis result: With the default synthesis flow of ChipVerify Lab (Yosys with the SkyWater 130 nm high-density cell library), this module builds 8 flip-flops, all for sum_q, because it is the only signal assigned on a clock edge. The other 66 cells are combinational logic: the adder that drives sum, the comparator and multiplexer that drive larger, and the inverters that drive a_inv. sum, larger and a_inv are declared exactly like sum_q, but none of them holds a value of its own.
Common Mistakes
Mistake #1: Assuming a logic variable can have multiple drivers
A plain logic declaration is implicitly a variable, and variables are limited to a single structural driver — full stop. Both of the patterns below are illegal for exactly that reason.
module tb;
logic data; // implicitly a variable: var logic data;
assign data = 1'b1; // Driver #1 (continuous)
initial
data = 1'b0; // Driver #2 (procedural) -- illegal: can't mix continuous and procedural drivers on a variable
endmodule
module tb;
logic data;
assign data = 1'b1; // Driver #1
assign data = 1'b0; // Driver #2 -- also illegal: a variable can't have two continuous drivers either
endmodule
The fix isn't to avoid logic — it's to make data a net instead of a variable:
module tb;
wire logic data; // now a net of type logic, not a variable
assign data = 1'b1; // Driver #1
assign data = 1'b0; // Driver #2 -- legal: nets support multiple drivers, resolved by strength
endmodule
Declaring data as wire logic (or just wire) makes it a net, and nets are explicitly designed to support multiple drivers — exactly what's needed for something like a shared tri-state bus.
Mistake #2: Thinking logic and reg are different value systems
As a data type, logic is identical to reg — same 4-state value set, and in SystemVerilog, the same rules: a plain reg variable can technically take a single continuous assign too, since it's the same variable type as logic under a different keyword (this wasn't allowed in classic Verilog, where reg was procedural-only). The real, practical difference is object kind flexibility: reg is essentially always used as a variable, while logic can be paired with var (the default) or a net keyword like wire to become a net instead, as Common Mistake #1 shows.
Mistake #3: Assuming an undriven signal reads as 0
An undriven logic or reg reads as X, and an undriven wire reads as Z — see the refresher above. Neither is 0. Code that implicitly assumes a default of 0 can silently pass in simulation and only reveal the bug much later.
Mistake #4: Confusing logic with 2-state types
logic is a 4-state type — it can hold X and Z, just like reg. Don't confuse it with 2-state types like bit, which can only hold 0 and 1. See SystemVerilog bit, byte and int for more on 2-state types.
Practice Exercise
Challenge: A 2-to-1 Mux, Two Ways
Write a 2-to-1 multiplexer that selects between in0 and in1 based on sel, once using an always_comb block (procedural), and once more using a continuous assign with the ternary operator. Both versions should use logic for every signal.
Hint
For the assign version, the ternary form is assign out = sel ? in1 : in0;.
Solution
module tb;
logic sel, in0, in1;
logic out_proc, out_assign;
// Procedural version
always_comb begin
if (sel) out_proc = in1;
else out_proc = in0;
end
// Continuous assign version
assign out_assign = sel ? in1 : in0;
initial begin
in0 = 1'b0; in1 = 1'b1;
sel = 1'b0; #1;
$display ("sel=%0b out_proc=%0b out_assign=%0b", sel, out_proc, out_assign);
sel = 1'b1; #1;
$display ("sel=%0b out_proc=%0b out_assign=%0b", sel, out_proc, out_assign);
end
endmodule
Summary
In this tutorial, you learned:
- 4-state values were already covered in Verilog Data Types —
0,1,X, andZ; undriven nets default toZ, undriven variables default toX logicis a 4-state data type, identical in value set toreg— it isn't a variable or a net by itself- A plain
logic a;declaration implicitly creates a variable (var logic a;), which is why it behaves likeregby default: driven by one procedural block, or one continuous assign, but never both and never more than one wire logic a;declares a net of typelogicinstead, which supports multiple drivers resolved by strength, just like any other net- A signal driven purely inside
always_comb, or purely by continuousassignstatements, works exactly the same whether it's declaredlogicor the equivalent old-stylereg/wire
By default, a coverpoint creates one automatic bin per legal value of whatever it's tracking. The bins construct lets you take control of that instead — grouping values into a single bin, splitting a range across a fixed number of bins, or catching anything left over with a default bin.
7 min read | Intermediate Level
What You'll Learn
- The different bin types: manual single-value bins, automatic bins over a whole range, a fixed number of automatic bins, and a default catch-all bin
- How coverage percentage is calculated once a coverpoint has multiple bins
- How SystemVerilog splits a range across a fixed number of automatic bins, including uneven splits
- How array bins (
[]) differ from a single named bin covering the same range
Bin Syntax Reference
Here's the full range of ways a bins block can be written, all in one place:
coverpoint mode {
// Manually create a separate bin for each value
bins zero = {0};
bins one = {1};
// Allow SystemVerilog to automatically create separate bins for each value
// Values from 0 to maximum possible value is split into separate bins
bins range[] = {[0:$]};
// Create automatic bins for both the given ranges
bins c[] = { [2:3], [5:7]};
// Use fixed number of automatic bins. Entire range is broken up into 4 bins
bins range[4] = {[0:$]};
// If the number of bins cannot be equally divided for the given range, then
// the last bin will include remaining items; Here there are 13 values to be
// distributed into 4 bins which yields:
// [1,2,3] [4,5,6] [7,8,9] [10, 1, 3, 6]
bins range[4] = {[1:10], 1, 3, 6};
// A single bin to store all other values that don't belong to any other bin
bins others = default;
}
The rest of this article walks through four of these styles with a working example and real coverage results for each, using a 3-bit variable mode (legal values 0 through 7) sampled at the same five points in every example: 4, 1, 1, 3, 5.
Manually Declaring Individual Bins
The simplest case: name a bin and give it exactly one value to watch for.
module tb;
bit [2:0] mode;
// This covergroup does not get sample automatically because
// the sample event is missing in declaration
covergroup cg;
coverpoint mode {
bins one = {1};
bins five = {5};
}
endgroup
// Stimulus : Simply randomize mode to have different values and
// manually sample each time
initial begin
cg cg_inst = new();
for (int i = 0; i < 5; i++) begin
#10 mode = $random;
$display ("[%0t] mode = 0x%0h", $time, mode);
cg_inst.sample();
end
$display ("Coverage = %0.2f %%", cg_inst.get_inst_coverage());
end
endmodule
Output
ncsim> run [10] mode = 0x4 [20] mode = 0x1 [30] mode = 0x1 [40] mode = 0x3 [50] mode = 0x5 Coverage = 100.00 % ncsim: *W,RNQUIE: Simulation is complete.
Both one (hit when mode is 1) and five (hit when mode is 5) were sampled at least once across the 5 samples, so both of the coverpoint's 2 bins are covered — 2/2 = 100%.
Quick Check
Q: If a third bin, bins nine = {9};, were added to the example above, what would the new coverage percentage be (given the same 5 sampled values)?
Show Answer
66.67% — there are now 3 bins total, and nine is never hit since 9 isn't a legal value for a 3-bit variable anyway (0–7), so only 2 of the 3 bins are covered.
Automatic Bins Across a Full Range
Adding [] after a bin name tells SystemVerilog to automatically create one bin per value across the given range, instead of one bin for the whole range:
covergroup cg;
coverpoint mode {
// Declares a separate bin for each values -> Here there will 8 bins
bins range[] = {[0:$]};
}
endgroup
Output
ncsim> run [10] mode = 0x4 [20] mode = 0x1 [30] mode = 0x1 [40] mode = 0x3 [50] mode = 0x5 Coverage = 50.00 % ncsim: *W,RNQUIE: Simulation is complete.
4 out of the total possible 8 values (0 through 7) have been sampled — 0x4, 0x1, 0x3, and 0x5 — and hence coverage is 4/8 = 50%.
A Fixed Number of Automatic Bins
Instead of one bin per value, you can ask for a specific number of bins and let SystemVerilog split the range between them:
covergroup cg;
coverpoint mode {
// Declares 4 bins for the total range of 8 values
// So bin0->[0:1] bin1->[2:3] bin2->[4:5] bin3->[6:7]
bins range[4] = {[0:$]};
}
endgroup
Output
ncsim> run [10] mode = 0x4 [20] mode = 0x1 [30] mode = 0x1 [40] mode = 0x3 [50] mode = 0x5 Coverage = 75.00 % ncsim: *W,RNQUIE: Simulation is complete.
mode never got a value of 6 or 7, so the bin covering [6:7] is never hit. The other three bins — [0:1], [2:3], and [4:5] — each caught at least one of the sampled values, so 3 out of 4 bins are covered: 75%.
Splitting a Fixed Number of Bins Across a Custom Value List
A fixed number of bins doesn't have to divide a plain contiguous range — it can just as easily divide a mixed list of ranges and individual values:
covergroup cg;
coverpoint mode {
// Defines 3 bins
// 5 total values (1,2,3,4 from the range, plus 7) split across 3 bins:
// the first 2 bins get 1 value each, and the last bin absorbs the rest
// bin1->1 bin2->2, bin3->[3,4,7]
bins range[3] = {[1:4], 7};
}
endgroup
Output
ncsim> run [10] mode = 0x4 [20] mode = 0x1 [30] mode = 0x1 [40] mode = 0x3 [50] mode = 0x5 Coverage = 66.67 % ncsim: *W,RNQUIE: Simulation is complete.
Only 2 of the 3 bins were hit: bin1 (just the value 1) caught the sampled 1s, and bin3 (values 3, 4, and 7 — the leftover items from the uneven split) caught the sampled 3 and 4. bin2, watching only the value 2, was never hit — so coverage is still 2/3 = 66.67%.
Both this example and the reference snippet at the top of this article follow the exact same rule: the first N−1 bins each get an equal, floor-divided share of the values, and the last bin absorbs whatever's left over. With 5 values split 3 ways that's 1, 1, 3; with 13 values split 4 ways (the reference snippet) it's 3, 3, 3, 4. The split is only even when the total divides cleanly by the bin count — otherwise the last bin ends up noticeably larger than the rest.
Quick Check
Q: Using bins range[] = {[0:$]} versus bins range = {[0:$]} (no square brackets) on the same 3-bit variable — how many bins does each create?
Show Answer
range[] creates 8 separate bins, one per legal value. range without the brackets creates just 1 bin covering the entire range — it's hit as soon as mode takes any value from 0 to 7.
Where Do Custom Bins Matter?
Custom bins are what make coverage practical on wide fields — grouping a 32-bit address into a handful of named legal windows (like low_region, high_region, reserved) gives a meaningful, reviewable coverage report, where one automatic bin per address value would be both impractical to create and useless to read.
Common Beginner Mistakes
Mistake #1: Forgetting the [] for one bin per value
bins name = {[0:7]}; creates a single bin covering the entire range, while bins name[] = {[0:7]}; creates 8 separate bins, one per value. Why? It's a one-character difference with a big effect on what gets measured — the first version is hit by any value 0 through 7, while the second requires every individual value to be seen before it's fully covered.
Mistake #2: Assuming a fixed number of bins always splits a range evenly
The first N−1 bins each get an equal, floor-divided share of the values; the last bin always absorbs whatever's left over. Why? If the total number of values doesn't divide cleanly by the bin count, the last bin ends up noticeably larger than the others — work out that division before assuming a specific, even split.
Mistake #3: Treating a default bin as an error catch
bins others = default; simply collects any legal value that isn't claimed by one of the coverpoint's other explicit bins. Why? It has nothing to do with detecting invalid or illegal values — for that, SystemVerilog has a separate illegal_bins construct; a plain default bin just quietly picks up whatever's left.
Practice Exercise
Challenge: Split a 4-Bit Variable Into 2 Automatic Bins
Given a 4-bit variable addr (legal values 0 through 15), write a coverpoint with a fixed number of automatic bins that splits the full range into exactly 2 bins.
Hint
Use the same bins name[N] = {[0:$]}; pattern shown in the "Fixed Number of Automatic Bins" example, just with a different bin count.
Solution
covergroup cg;
coverpoint addr {
bins range[2] = {[0:$]};
}
endgroup
With 16 legal values split evenly across 2 bins, you'd expect bin0 to cover [0:7] and bin1 to cover [8:15] — each bin is hit as soon as any one value in its half of the range has been sampled.
Summary
In this tutorial, you learned:
- A manually declared bin (
bins name = {value};) tracks exactly one value - Adding
[]to a bin name (bins name[] = {range};) creates one automatic bin per value in that range, instead of a single bin for the whole range - A fixed number of bins (
bins name[N] = {range};) splits a range or value list acrossNbins, though the split isn't always perfectly even - A
defaultbin catches any legal value not claimed by another explicit bin — it's not related to error or illegal-value detection - Coverage percentage is always bins hit ÷ total bins, once you know how many bins a coverpoint actually has
Continuing the Functional Coverage Chapter
Continue with SystemVerilog Cross Coverage to track combinations of values across multiple coverpoints at once.
There's a third variant of fork...join: fork...join_none. It lets the parent thread resume execution of whatever follows the fork immediately, regardless of whether any of the forked threads have finished. Fork off five threads with join_none, and the parent thread continues right away while all five keep running in the background.
7 min read | Intermediate Level
What You'll Learn
- How
fork...join_nonediffers from plainfork...joinin when the parent thread resumes - How
join_nonebehaves when nested inside another fork - Why a task called concurrently from multiple
join_nonethreads needs to be declaredautomatic - Exactly what happens, step by step, when a shared (non-automatic) task's variables get overwritten by concurrent calls
- Why forking inside a loop needs its own fresh copy of the loop variable per iteration, and how that differs from the automatic-task fix
Syntax
fork
// Thread 1
// Thread 2
// ...
// Thread N
join_none
A Basic fork...join_none Example
module tb;
initial begin
$display ("[%0t] Main Thread: Fork join going to start", $time);
fork
print (20, "Thread1_0");
print (30, "Thread1_1");
print (10, "Thread2");
join_none
$display ("[%0t] Main Thread: Fork join has finished", $time);
end
// Note that we need automatic task
task automatic print (int _time, string t_name);
#(_time) $display ("[%0t] %s", $time, t_name);
endtask
endmodule
Output
ncsim> run [0] Main Thread: Fork join going to start [0] Main Thread: Fork join has finished [10] Thread2 [20] Thread1_0 [30] Thread1_1 ncsim: *W,RNQUIE: Simulation is complete.
Unlike plain fork...join, the main thread doesn't wait for anything here — "Main Thread: Fork join has finished" prints at 0ns, immediately after the fork statement, while Thread1_0, Thread1_1, and Thread2 keep running independently in the background and print later, each according to its own delay.
Quick Check
Q: If all three print() calls above were changed to use a delay of #0 instead of 10/20/30, would "Main Thread: Fork join has finished" still print before any of the three print() outputs?
Show Answer
Yes. join_none always lets the parent thread continue immediately after the fork statement itself, regardless of how long — or how short — the forked threads take. The parent's own next statement isn't waiting on anything the forked threads do.
Nested fork...join_none
module tb;
initial begin
$display ("[%0t] Main Thread: Fork join going to start", $time);
fork
begin
fork
print (20, "Thread1_0");
print (30, "Thread1_1");
join_none
$display("[%0t] Nested fork has finished", $time);
end
print (10, "Thread2");
join_none
$display ("[%0t] Main Thread: Fork join has finished", $time);
end
// Note that we need automatic task
task automatic print (int _time, string t_name);
#(_time) $display ("[%0t] %s", $time, t_name);
endtask
endmodule
Output
ncsim> run [0] Main Thread: Fork join going to start [0] Main Thread: Fork join has finished [0] Nested fork has finished [10] Thread2 [20] Thread1_0 [30] Thread1_1 ncsim: *W,RNQUIE: Simulation is complete.
The outer fork...join_none spawns the begin/end block and Thread2, then the main thread continues immediately without waiting for either. Inside the begin/end block, the inner fork...join_none spawns Thread1_0 and Thread1_1 in the background, and since that's also join_none, the block doesn't wait for them either — it immediately continues to print "Nested fork has finished," which is why that line shows up at 0ns too, right alongside the main thread's own completion message.
Why Do We Need an automatic Task?
Without the automatic keyword, the same display task called with different string arguments can end up printing the same message every time. This happens because multiple threads calling the same non-automatic (static) task share one single copy of its arguments and local variables in simulator memory. For each thread to get its own independent copy, the task needs to be declared automatic:
module tb;
initial begin
$display ("[%0t] Main Thread: Fork join going to start", $time);
fork
print (20, "Thread1_0");
print (30, "Thread1_1");
print (10, "Thread2");
join_none
$display ("[%0t] Main Thread: Fork join has finished", $time);
end
// Note that this is not an automatic task, its static
task print (int _time, string t_name);
#(_time) $display ("[%0t] %s", $time, t_name);
endtask
endmodule
Output
ncsim> run [0] Main Thread: Fork join going to start [0] Main Thread: Fork join has finished [10] Thread2 [20] Thread2 [30] Thread2 ncsim: *W,RNQUIE: Simulation is complete.
Every one of the three delayed prints now shows "Thread2" — even the ones originally called with "Thread1_0" and "Thread1_1" — but the delay times (10, 20, 30) still match each call correctly. Here's why both things happen at once:
All three forked calls to print begin executing at 0ns, one after another, since none of them have blocked yet. Each call's #(_time) delay is evaluated immediately as that call reaches it — before yielding to the next spawned call — so each thread correctly latches its own delay duration (10, 20, or 30ns) before suspending. But t_name is only read later, inside $display, which executes after the delay completes. By the time any of the three delays actually finish, all three calls have already run their initial setup and overwritten the single shared copy of t_name — and since print(10, "Thread2") is the last of the three calls to execute that setup, "Thread2" is whatever's left in shared storage when every delayed $display eventually fires.
Where Is fork...join_none Used?
fork...join_none is the usual way to launch a persistent background task — a monitor that watches a signal for the rest of the test, or a scoreboard that keeps checking results as they arrive — without blocking the main sequence of test steps that follows. It's often paired with a forever loop inside the forked thread to keep that background task running indefinitely.
Forking Inside a Loop
A related but different gotcha shows up when you fork directly inside a loop, without any task at all — spawning a batch of similar background processes is an extremely common pattern in testbenches:
module tb;
initial begin
for (int i = 0; i < 5; i++) begin
fork
#10 $display ("[%0t] i = %0d", $time, i);
join_none
end
#20 $finish;
end
endmodule
The intent here is five processes, each printing a different value of i (0 through 4). In practice, most or all of them end up printing the same value — typically the last one the loop reached. This isn't the same bug as a non-automatic task from the example above: there's no task here at all. The problem is that i itself is a single storage location that the loop keeps incrementing, and every forked process just holds a reference to that one variable — not a snapshot of whatever value it happened to hold at fork time. By the time any of the #10-delayed $display statements actually execute, the loop has already finished, and i holds whatever value it ended on.
The fix is to give each loop iteration its own independent copy of the value, and fork off of that copy instead of the loop variable itself:
module tb;
initial begin
for (int i = 0; i < 5; i++) begin
automatic int j = i; // a fresh copy, local to this iteration
fork
#10 $display ("[%0t] j = %0d", $time, j);
join_none
end
#20 $finish;
end
endmodule
Because j is declared automatic inside the loop body, a brand-new copy of it is created on every single iteration, and each forked process captures its own iteration's copy rather than sharing one variable with all the others. This time, all five processes correctly print their own distinct value.
This is the same underlying idea as declaring a task automatic — giving each concurrent user of a variable its own independent storage — just applied to a loop variable instead of a task's arguments. There's no task involved here at all, so the fix is a different pattern: an automatic local re-declared fresh on every loop iteration, not an automatic task.
Quick Check
Q: In the broken (non-automatic) version above, what value would you expect most or all five forked processes to print?
Show Answer
5. The for loop's exit condition is i < 5, so the loop increments i to 5 before the condition fails and the loop ends — by the time any of the delayed $display statements fire, i has already reached that final value.
Common Beginner Mistakes
Mistake #1: Assuming join_none waits for at least one thread
join_none waits for zero threads — the parent continues immediately after the fork statement. Why? If you actually need the parent to wait for at least one thread to finish before continuing, that's fork...join_any instead, covered next in this chapter.
Mistake #2: Forgetting automatic on a task called concurrently
As the example above shows in detail, a non-automatic task called from multiple concurrently forked threads shares a single copy of its variables, and later calls silently overwrite earlier ones. Why? This produces output that's still individually timed correctly but carries the wrong data — a subtle bug that's easy to miss if you're not specifically checking the printed values against the expected calls.
Mistake #3: Not accounting for leftover background threads
Threads spawned with join_none keep running after the parent moves on, and nothing automatically cleans them up. Why? If a test finishes without explicitly waiting for (wait fork) or terminating (disable fork) those background threads, they can still be active when the simulation ends, which is rarely what was intended.
Mistake #4: Forking inside a loop without capturing a fresh copy of the loop variable
As the "Forking Inside a Loop" section above shows, every process forked from inside a loop shares the loop variable itself unless you explicitly snapshot it into a fresh automatic local first. Why? Since forking doesn't automatically copy anything, all the spawned processes end up seeing whatever value the loop variable holds by the time they actually run — usually its final value, not the one that was current when each was forked.
Practice Exercise
Challenge: Fix the Broken Task
Using the broken, non-automatic version of print from the "Why Do We Need an automatic Task?" section, predict what the output would look like if the three calls inside the fork were reordered to print(30, "Thread1_1"), print(10, "Thread2"), print(20, "Thread1_0") — still without the automatic keyword.
Hint
The delay times still latch correctly per call, in the order given. The shared t_name ends up holding whatever the last call in the fork block wrote to it, regardless of delay length.
Solution
All three delayed prints would show "Thread1_0", since that's now the last call listed in the fork block: the output would print at 10ns, 20ns, and 30ns respectively (matching each call's own delay), but every line would read "Thread1_0" instead of its original intended name — the same shared-storage overwrite bug, just landing on a different name because the call order changed.
Summary
In this tutorial, you learned:
fork...join_nonelets the parent thread resume immediately after theforkstatement, without waiting for any spawned thread to finish- Threads spawned with
join_nonecontinue running independently in the background - A nested
fork...join_nonebehaves the same way at every level — neither the inner nor outer fork blocks its containing thread - A task called concurrently from multiple threads must be declared
automatic, or all calls will share one copy of its local variables - A delay value used to control timing (like
#(_time)) is latched immediately when reached, but a variable only read later (like inside a delayed$display) can be overwritten by other concurrent calls before it's ever used - Forking inside a loop shares the loop variable across every spawned process unless you snapshot it into a fresh
automaticlocal declared inside the loop body first
Continuing the Threads & Processes Chapter
Continue with SystemVerilog fork join_any, wait fork, and disable fork join for waiting on or cleaning up background threads like the ones in this article.
A forever loop runs forever, or for infinite simulation time. It has no condition and never ends on its own. That makes it the natural choice for testbench processes that must stay alive for the whole test, such as clock generators, drivers and monitors. It also means every forever loop needs two things: a timing control inside the body, and a way to stop.
6 min read | Intermediate Level
What You'll Learn
- The syntax of
foreverand how it differs from analwaysblock - Why a
foreverloop without a timing control hangs the simulator - How to build clocks and monitors with
forever - How to stop a
foreverloop cleanly
Syntax
forever
// Single statement
forever begin
// Multiple statements
end
forever takes no arguments. It is the same as while (1) or for (;;), but it states the intent more clearly.
forever vs always
A forever loop behaves much like the Verilog always block below. Both run for infinite simulation time, and both must contain a delay or event control.
always
// Single statement
always begin
// Multiple statements
end
An always or forever block without a delay element will hang the simulation. The simulator only moves time forward when every process is waiting. A loop that never waits keeps running at the same timestamp, and no other process gets a turn.
The difference is where each one may appear:
always | forever | |
|---|---|---|
| What it is | A procedural block, declared directly in a module, interface or program | A loop statement, used inside a procedural block or task |
| Allowed in classes or tasks? | No | Yes |
| Can be exited? | No, it runs until the simulation ends | Yes, with break, disable or by killing its process |
| Synthesizable? | Yes, as always_ff, always_comb and so on | No |
Because an always block cannot be placed inside a class or another procedural block, class-based testbenches use a forever loop inside a task to get the same effect.
Example: Clock Generation
A free-running clock is the classic use of forever. The loop toggles the clock after every half-period delay.
module tb;
bit clk; // 2-state, starts at 0
initial begin
forever #5 clk = ~clk; // toggle every 5 ns: 10 ns period (100 MHz)
end
initial begin
#50 $finish; // the clock loop never ends, so stop here
end
endmodule
The clock rises at 5, 15, 25, 35 and 45 ns. The second initial block is essential: without $finish, the clock would keep the simulation running forever.
Example: A Testbench Monitor
The pseudo code below sketches a testbench monitor. Once started, it keeps running for as long as there is activity on the bus it watches.
class Monitor;
virtual task run();
forever begin
@(posedge vif.clk);
if (vif.write & vif.sel)
// Capture write data
if (!vif.write & vif.sel)
// Capture read data
end
endtask
endclass
module tb;
Monitor mon = new();
// Start the monitor task and allow it to continue as
// long as there is activity on the bus
initial begin
fork
mon.run();
join_none
end
endmodule
@(posedge vif.clk)is the timing control. Each pass samples the bus once per clock and then waits for the next edge.fork ... join_nonestartsrun()as a separate process. Theinitialblock can then carry on instead of being stuck inside a task that never returns.
This is pseudo code. Comments are not statements, so as written the second if becomes the body of the first, and the second if has no body at all, which is a compile error. In real code, give each if its own statement or begin ... end block. vif would also need to be declared in the class as a virtual interface handle.
Where is forever used in verification?
Almost every reusable testbench component runs on a forever loop. A driver repeatedly fetches the next transaction and drives it onto the pins. A monitor repeatedly samples the interface and sends observed transactions to a scoreboard. In UVM, the run_phase of drivers and monitors is typically a single forever loop.
Quick Check
Q: What would happen if the testbench called mon.run(); directly inside the initial block, without fork ... join_none?
Show Answer
The monitor would still run, but run() never returns. Any statements after the call in that initial block, such as starting a test sequence, would never execute.
Stopping a forever Loop
A forever loop has no exit condition, so something must end it explicitly:
$finishends the whole simulation, as in the clock example.breakinside the loop exits just that loop, and execution continues after it.disableon a named block, ordisable fork, stops the loop from another process. See disable fork.
module tb;
bit clk, done;
int cycles;
always #5 clk = ~clk; // clock rises at 5, 15, 25 ... ns
initial #73 done = 1; // some other process signals completion
initial begin
forever begin
@(posedge clk);
cycles++;
if (done) break; // leave the loop on the first edge after done
end
// Runs only after break: prints "Loop exited after 8 cycles at 75"
$display ("Loop exited after %0d cycles at %0t", cycles, $time);
$finish;
end
endmodule
done goes high at 73 ns. The loop sees it on the next rising edge at 75 ns, which is the eighth edge, and break hands control to the $display after the loop.
forever in Digital Design
forever is a verification-only construct, and mainstream synthesis tools do not accept it in RTL. Hardware that "runs forever" is described with always_ff for clocked logic and always_comb for combinational logic (see always_comb and always_ff). Design engineers still use forever in their own block-level testbenches to generate clocks and apply stimulus.
Common Beginner Mistakes
Mistake #1: Waiting on a level that is already true
Wrong: forever begin wait (ready); send_item(); end
Right: forever begin @(posedge clk); if (ready) send_item(); end
Why? wait (ready) does not block if ready is already 1. If send_item() also takes no time, the loop spins at the same timestamp and hangs, even though it appears to contain a timing control. Make sure every pass is guaranteed to advance time, for example by waiting on a clock edge.
Mistake #2: Code after a forever loop that never runs
In initial begin forever #5 clk = ~clk; reset_dut(); end, reset_dut() is never called. Why? Statements after a forever loop run only if the loop is exited with break. Put the clock in its own initial block, or start the loop with fork ... join_none.
Mistake #3: No way to end the simulation
A testbench whose only processes are forever loops runs until you kill the simulator. Why? A free-running clock always has a future event scheduled, so the simulator never runs out of work. Always provide a $finish, or in UVM, drop all objections, once the test is done.
Practice Exercise
Challenge: 200 MHz clock that stops itself
Write a testbench that generates a 200 MHz clock with a forever loop and ends the simulation after exactly 20 rising edges.
Hint
200 MHz means a 5 ns period, so the half-period delay is 2.5 ns. You need a `timescale with a precision fine enough for 2.5 ns, and repeat to count the edges.
Solution
`timescale 1ns/1ps
module tb;
bit clk;
initial forever #2.5 clk = ~clk; // 2.5 ns half period = 5 ns period (200 MHz)
initial begin
repeat (20) @(posedge clk); // count 20 rising edges
$finish; // 20th edge is at 2.5 + 19*5 = 97.5 ns
end
endmodule
The clock loop and the edge counter run as two separate processes. The counter is what ends the test, because the clock loop never would.
Summary
In this tutorial, you learned:
foreverrepeats its body indefinitely and is equivalent towhile (1)- Every pass must advance simulation time, through
#delayor@(event), or the simulator hangs - Unlike
always,forevercan be used inside tasks and classes, which is why drivers and monitors use it - Start long-running
forevertasks withfork ... join_noneso the calling block can continue - A
foreverloop ends only throughbreak,disableor$finish foreveris not synthesizable; RTL usesalways_ffandalways_combinstead
forever, repeat, while, for, do while and foreach. Each one suits a different job. Pick the wrong one and you can hang your simulation or get hardware you never intended.This article walks through all six. It covers their syntax, how the simulator runs them, and which ones belong in synthesizable RTL versus testbench code only.
8 min read | Intermediate Level
What You'll Learn
- The six looping constructs in SystemVerilog and when to use each one
- Why a loop without timing control can hang a simulation
- Which loops are used in synthesizable RTL and which are testbench-only
- How to exit or skip loop iterations early
What Are Loops?
A loop is a block of code that executes repeatedly. Most loops have a condition that decides when to stop. Get that condition wrong, or leave it out, and the loop never ends.
The table below summarizes all six constructs before we look at each one:
| Construct | Behavior | Typical use |
|---|---|---|
forever | Runs the statements forever; needs an external exit | Clock generators, monitors, drivers |
repeat | Runs the statements a fixed number of times | Send N transactions, wait N clocks |
while | Repeats while a condition is true; checked before each pass | Wait until a status flag changes |
for | Initialization, condition and step on one line | Indexed loops in RTL and testbenches |
do while | Runs at least once, then repeats while the condition is true | Retry an operation until it succeeds |
foreach | Iterates over every element of an array automatically | Walk arrays, queues and scoreboards |
forever
The forever loop is an infinite loop, equivalent to while (1). Because it never exits on its own, its body almost always contains a timing control such as #5 or @(posedge clk). Without one, the loop runs every iteration at the same simulation time, simulation time never advances, and the simulator appears to hang.
module tb;
// This initial block has a forever loop which will "run forever"
// Hence this block will never finish in simulation
initial begin
forever begin
#5 $display ("Hello World !");
end
end
// Because the other initial block will run forever, our simulation will hang!
// To avoid that, we will explicity terminate simulation after 50ns using $finish
initial
#50 $finish;
endmodule
ncsim> run Hello World ! Hello World ! Hello World ! Hello World ! Hello World ! Hello World ! Hello World ! Hello World ! Hello World ! Simulation complete via $finish(1) at time 50 NS + 0
The message prints at 5, 10, ... 45 ns, which is nine times. At 50 ns the $finish in the second initial block ends the run. Without it, simulation would continue indefinitely.
forever is a testbench construct. It is the standard way to build a free-running clock or a monitor that runs for the whole test. See SystemVerilog forever loop for clock generation and monitor examples.
repeat
The repeat loop runs a block a fixed number of times, then exits. There is no loop variable or condition to manage. The example below prints the message 5 times and then carries on with the rest of the code.
module tb;
// This initial block will execute a repeat statement that will run 5 times and exit
initial begin
// Repeat everything within begin end 5 times and exit "repeat" block
repeat(5) begin
$display ("Hello World !");
end
end
endmodule
ncsim> run Hello World ! Hello World ! Hello World ! Hello World ! Hello World ! ncsim: *W,RNQUIE: Simulation is complete.
repeat (3) @(posedge clk); uses the same loop with an event control as its only statement. It does nothing except wait for three rising clock edges. It is the shortest way to wait a fixed number of cycles in a testbench.
See SystemVerilog repeat for more examples.
while
The while loop checks its condition before every pass, so the body may run zero or more times. In the example below, counter starts at zero and is incremented on every rising clock edge until it reaches 10.
module tb;
bit clk;
always #10 clk = ~clk;
initial begin
bit [3:0] counter;
$display ("Counter = %0d", counter); // Counter = 0
while (counter < 10) begin
@(posedge clk);
counter++;
$display ("Counter = %0d", counter); // Counter increments
end
$display ("Counter = %0d", counter); // Counter = 10
$finish;
end
endmodule
ncsim> run Counter = 0 Counter = 1 Counter = 2 Counter = 3 Counter = 4 Counter = 5 Counter = 6 Counter = 7 Counter = 8 Counter = 9 Counter = 10 Counter = 10 Simulation complete via $finish(1) at time 190 NS + 0
The clock rises at 10, 30, 50 ns and so on. Ten rising edges are needed to count to 10, so the loop ends at 190 ns. The last Counter = 10 line comes from the $display after the loop.
for
The for loop works like its counterpart in Verilog and C. The starting value, exit condition and step expression are all written on one line, which makes it compact and the most widely used loop form.
module tb;
bit clk;
always #10 clk = ~clk;
initial begin
bit [3:0] counter;
$display ("Counter = %0d", counter); // Counter = 0
for (counter = 2; counter < 14; counter = counter + 2) begin
@(posedge clk);
$display ("Counter = %0d", counter); // Counter increments
end
$display ("Counter = %0d", counter); // Counter = 14
$finish;
end
endmodule
ncsim> run Counter = 0 Counter = 2 Counter = 4 Counter = 6 Counter = 8 Counter = 10 Counter = 12 Counter = 14 Simulation complete via $finish(1) at time 110 NS + 0
The body runs for counter values 2, 4, 6, 8, 10 and 12, which is six clock edges ending at 110 ns. After the last step counter is 14, the condition fails, and the final $display prints 14.
Of all the loops here, for matters most for RTL design. When the bounds are constants and the body has no timing control, the synthesis tool unrolls the loop. It replicates the body once per iteration and builds hardware for every copy. Do not confuse this with a generate for loop, which uses a genvar and replicates module instances or assign statements at elaboration time.
Where is the for loop used in design?
Wide bit-level operations, such as reducing a 32-bit bus to a parity bit or finding the highest-priority request in an arbiter, are usually written as a for loop inside always_comb. The synthesis tool unrolls the loop into a chain or tree of gates, one slice per iteration.
See SystemVerilog for loop for loop variable scope and multiple loop variables.
do while
A do while loop executes the body first and checks the condition afterwards. The body always runs at least once, even if the condition is false from the start.
module tb;
bit clk;
always #10 clk = ~clk;
initial begin
bit [3:0] counter;
$display ("Counter = %0d", counter); // Counter = 0
do begin
@ (posedge clk);
counter ++;
$display ("Counter = %0d", counter); // Counter increments
end while (counter < 5);
$display ("Counter = %0d", counter); // Counter = 5
$finish;
end
endmodule
ncsim> run Counter = 0 Counter = 1 Counter = 2 Counter = 3 Counter = 4 Counter = 5 Counter = 5 Simulation complete via $finish(1) at time 90 NS + 0
In testbenches, while and do while nearly always wait on a clock or event inside the body, as above. That makes them testbench-only. See SystemVerilog while and do-while loop for help choosing between the two.
foreach
The foreach loop is built for walking arrays. You don't declare an index variable or track the array size. The loop variable is declared automatically and steps through every valid index of the array.
module tb_top;
bit [7:0] array [8]; // Create a fixed size array
initial begin
// Assign a value to each location in the array
foreach (array [index]) begin
array[index] = index;
end
// Iterate through each location and print the value of current location
foreach (array [index]) begin
$display ("array[%0d] = 0x%0d", index, array[index]);
end
end
endmodule
ncsim> run array[0] = 0x0 array[1] = 0x1 array[2] = 0x2 array[3] = 0x3 array[4] = 0x4 array[5] = 0x5 array[6] = 0x6 array[7] = 0x7 ncsim: *W,RNQUIE: Simulation is complete.
The format string uses 0x%0d, which prints a decimal value after a literal "0x". The output looks correct here only because 0 to 7 are the same in decimal and hex. Use %0h when you actually want hexadecimal.
Most synthesis tools accept foreach over a fixed-size array, because its iteration count is known at elaboration and it unrolls just like a bounded for loop. See SystemVerilog foreach loop for multidimensional arrays.
Quick Check
Q: Why does the forever example need #5 inside the loop, and a separate $finish elsewhere?
Show Answer
Without #5, every iteration would run at time 0 and simulation time would never advance. The separate $finish is needed because forever has no exit condition of its own, so something outside the loop must stop the simulation.
Exiting a Loop Early
Any of the six loops can be cut short. break leaves the innermost loop immediately, and continue skips the rest of the current iteration and moves on to the next one. These are how a testbench leaves a forever loop cleanly, for example when a timeout counter expires. See SystemVerilog break and continue for details.
Loops in Design vs Verification
| Construct | RTL design (synthesizable) | Verification |
|---|---|---|
for | Yes, with constant bounds and no timing control | Yes |
foreach | Yes, over fixed-size arrays in most tools | Yes, including dynamic arrays, queues and associative arrays |
repeat | Some tools accept a constant count; for is the portable choice | Yes |
while, do while | Only if the tool can work out a fixed iteration count; best avoided | Yes |
forever | No | Yes |
Where are loops used in verification?
Constrained-random tests use repeat to send a fixed number of randomized transactions, and forever inside drivers and monitors that run for the whole test. Scoreboards use foreach to walk queues and associative arrays when comparing expected and actual results.
Common Beginner Mistakes
Mistake #1: Missing timing control in forever or while
A forever loop, or a while loop whose condition depends on another process, with no #delay or @(posedge clk) inside it runs every iteration at the same simulation time. Other processes never get to run, so the condition never changes and the run hangs. Why? The simulator only moves time forward when every active process is waiting.
Mistake #2: Treating while and do while as the same
A while loop checks first and may never run its body. A do while loop always runs its body at least once. Why? Mixing them up causes off-by-one errors in transaction or retry counts.
Mistake #3: Using data-dependent loops in RTL
A while loop whose exit depends on a signal value cannot be unrolled, because the tool cannot know how many copies of the hardware to build. Why? Synthesis creates hardware for every iteration up front. Use a for loop with constant bounds and put the data-dependent check inside it as an if.
Quick Check
Q: Which loop constructs are most commonly unrolled into synthesizable hardware?
Show Answer
for with constant bounds, and foreach over fixed-size arrays. Their iteration count is known at elaboration time, so the tool can build one copy of the logic per iteration.
Practice Exercise
Challenge: Convert a while loop to a for loop
Rewrite the while example above, which counts from 0 to 10, as a for loop that prints the same sequence of counter values on the same clock edges.
Hint
A for loop puts the starting value, the exit condition and the step on one line. The body only needs the @(posedge clk) and the $display.
Solution
module tb;
bit clk;
always #10 clk = ~clk;
initial begin
bit [3:0] counter;
$display ("Counter = %0d", counter);
for (counter = 0; counter < 10; counter++) begin
@(posedge clk);
$display ("Counter = %0d", counter+1);
end
$finish;
end
endmodule
Both versions print 0 to 10, one value per rising edge, and finish at 190 ns. In the for version the step runs at the end of each pass, after the $display, so the body prints counter+1 to show the value the step is about to produce. The original also printed 10 a second time after the loop; add a $display after the loop if you want that line too.
Summary
In this tutorial, you learned:
- SystemVerilog has six loop constructs:
forever,repeat,while,for,do whileandforeach foreverand condition-waitingwhileloops need a timing control in the body, or simulation hangsdo whilealways runs its body at least once;whilemay run it zero timesforwith constant bounds andforeachover fixed-size arrays are unrolled into hardware by synthesis toolsbreakandcontinuelet you leave a loop or skip an iteration earlyrepeat,foreverandforeachare workhorses of testbench code
Quiz
No quiz questions available for this article.