A struct gives every member its own separate storage. A union does the opposite.
Every member of a union shares the exact same storage. Only one interpretation of that storage is meaningful at a time. Writing through one member and then reading back through a different member reinterprets those same underlying bits as a different type.
11 min read | Intermediate Level
What You'll Learn
- How a union's members share the same storage, unlike a struct's separate storage per member
- Why a union's size equals its largest member, not the sum of all of them
- How a packed union lets you reinterpret the same bits as different types
- Why every member of a packed union must be exactly the same size
Union vs Struct: Shared Storage
Take a struct with a 16-bit member and an 8-bit member. It occupies at least 24 bits, because each member gets its own space.
Now take a union with those exact same two members. It occupies only 16 bits — the size of its largest member. Every member of a union is really just a different way of looking at the same storage, not separate storage of its own.
The diagram below shows the difference using these same numbers:
Design use: a union is a compact way to model hardware where the same bits genuinely mean different things depending on context, like a shared register field. Verification use: a union is handy in a testbench for reinterpreting a packet's raw bytes as a structured header without writing manual bit-slicing code.
Struct vs Union: Same Fields, Two Behaviors
You already know how a struct behaves, so start there as a quick recap. Here's a struct with a 32-bit raw field alongside a 16-bit high and a 16-bit low:
typedef struct packed {
bit [31:0] raw;
bit [15:0] high;
bit [15:0] low;
} data_struct_t;
module tb;
initial begin
data_struct_t d;
d.raw = 32'hDEAD_BEEF;
$display ("raw = 0x%0h", d.raw);
$display ("high = 0x%0h", d.high);
$display ("low = 0x%0h", d.low);
end
endmodule
raw = 0xdeadbeef high = 0x0 low = 0x0 - S i m u l a t i o n R e p o r t: Verilator 5.052 2026-09-05
The struct is 64 bits wide — 32 for raw, plus 16 for high, plus 16 for low — because each member gets its own separate space. Assigning d.raw only touches raw's own bits. high and low are untouched, so they still show their default value of 0.
Now here's the same idea, but as a union. A packed union is the most commonly used form in practice. It lets you view one fixed-width value either as a flat vector or as named sub-fields:
typedef union packed {
bit [31:0] raw;
struct packed {
bit [15:0] high; // declared first - occupies the upper (most significant) half
bit [15:0] low; // declared second - occupies the lower (least significant) half
} halves;
} data_t;
module tb;
initial begin
data_t d;
d.raw = 32'hDEAD_BEEF;
$display ("raw = 0x%0h", d.raw);
$display ("high = 0x%0h", d.halves.high);
$display ("low = 0x%0h", d.halves.low);
end
endmodule
raw = 0xdeadbeef high = 0xdead low = 0xbeef - S i m u l a t i o n R e p o r t: Verilator 5.052 2026-09-05
This prints raw = 0xdeadbeef, high = 0xdead, low = 0xbeef — a very different result from the struct version above, even though the assignment looks the same.
Nothing was actually copied or split apart here. raw and halves occupy the exact same 32 bits of storage. Assigning through raw and reading back through halves.high and halves.low is just viewing those same bits through a different, more structured lens.
As with a packed struct, the first-declared member of the inner struct — high — occupies the most significant bits. The diagram below shows exactly how the 32 bits of 0xDEADBEEF break down into high and low:
Compare the two results: in the struct, assigning raw touched nothing else, so high and low stayed at 0. In the union, that same assignment instantly changed what high and low read back, because they were never separate storage to begin with. One assignment either touching everything or touching nothing is the entire practical difference between a union and a struct.
Quick Check
Q: If d.halves.low were assigned 16'h1234 directly, what would d.raw show afterward?
Show Answer
0xdead1234. Since raw and halves share the same storage, changing the lower 16 bits through halves.low is visible immediately through raw too — the upper 16 bits (0xdead, still held by halves.high) are untouched.
Why All Packed Untagged Union Members Must Be the Same Size
Every member of a packed, untagged union has to occupy exactly the same number of bits — a packed tagged union is explicitly exempt from this. In the example above, raw (a plain 32-bit vector) and halves (a 16+16-bit packed struct) are both exactly 32 bits wide.
This isn't a coincidence — it's a requirement for the untagged form specifically. A packed, untagged union has no way to represent "this member is only valid for part of the storage." Every member is understood to span the union's entire width, so they all have to actually be that width. A tagged union stores an explicit tag alongside the value, so it doesn't have this restriction — see "A Note on Tagged Unions" below.
A Note on Tagged Unions
The union shown above is untagged. Nothing stops you from writing through one member and reading back through a completely different one, as the example deliberately does.
A union tagged {...} is the type-checked alternative. It tracks which member was actually written, and only allows reading that same member back safely. If accidentally reading the wrong interpretation of a union's bits would be a real risk in a given piece of code, a tagged union removes that risk entirely — at the cost of losing the free-form reinterpretation this article's main example relies on.
Where Are Unions Used?
A packed union is a natural fit for a register model. It represents the same 32-bit register value as both a flat vector (for simple reads and writes) and a named-field breakdown (for readable access to individual control bits), without duplicating any storage or manually shifting and masking bits every time either view is needed.
On the verification side, a testbench can use the same trick to reinterpret a raw byte stream captured off a bus as a structured transaction, without writing a separate parser.
What It Synthesizes Into
All members of a packed union share the same bits, so the union costs nothing beyond the storage of one member. The register below is written through the word member and read through the bytes member.
module word_reg (
input logic clk, load,
input logic [31:0] d,
output logic [7:0] b2
);
typedef union packed {
logic [31:0] word;
logic [3:0][7:0] bytes;
} word_t;
word_t q;
always_ff @(posedge clk)
if (load) q.word <= d;
assign b2 = q.bytes[2];
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 with a built-in enable and nothing else. Reading q.bytes[2] is the same as reading q.word[23:16], and because no other bits are ever read, the tool removes the 24 flip-flops that would hold them. The same module written with a plain logic [31:0] q and q[23:16] builds the same 8 cells.
Common Beginner Mistakes
Mistake #1: Assuming a union's size is the sum of its members
That's how a struct works — a union is the opposite. Why? A union's size is always just the size of its single largest member, since every member shares that same storage rather than getting its own.
Mistake #2: Mixing different-sized members in a packed, untagged union
Every member of a packed, untagged union has to be exactly the same width — a packed tagged union is the one place this restriction doesn't apply. Why? An untagged packed union has no mechanism for a member that only covers part of the total storage, since there's no tag to say which member is actually valid — if the members genuinely need to be different sizes, a tagged union is the right tool instead.
Mistake #3: Forgetting that all members share the same bits
As the Quick Check shows, changing one member is immediately visible through every other member, since there's only one underlying storage location. Why? This is the entire point of a union, but it's easy to forget mid-code and accidentally assume two members hold independent values.
Mistake #4: Assuming an untagged union offers any type safety
Writing through one member and reading through a completely unrelated one always succeeds, with no checking at all. Why? If that flexibility is actually a risk in a specific context, a tagged union is the safer choice — an untagged union simply doesn't protect against it.
Practice Exercise
Challenge: Split a 16-bit Value Into Bytes
Define a packed union with a 16-bit word member and a packed struct member holding two 8-bit fields, msb and lsb. Assign word = 16'hA5C3; and predict what msb and lsb would each show.
Hint
Remember that the first-declared member of a packed struct occupies the most significant bits — decide which field needs to come first to match its name.
Solution
typedef union packed {
bit [15:0] word;
struct packed {
bit [7:0] msb;
bit [7:0] lsb;
} bytes;
} word_t;
module tb;
initial begin
word_t w;
w.word = 16'hA5C3;
$display ("msb=0x%0h lsb=0x%0h", w.bytes.msb, w.bytes.lsb);
end
endmodule
This prints msb=0xa5 lsb=0xc3. 16'hA5C3 splits into an upper byte 0xA5 and a lower byte 0xC3 — and since msb is declared first in the packed struct, it correctly lands on the upper (most significant) byte, matching its name.
Summary
In this tutorial, you learned:
- A union's members all share the same storage; a struct gives each member its own
- A union's size equals its largest member, not the sum of all its members
- A packed, untagged union requires every member to be exactly the same size, since none of them represent only part of the storage — a packed
taggedunion is exempt from this, since it tracks an explicit tag - Writing through one member and reading through another reinterprets the same bits — a technique packed unions are commonly used for, like viewing a register as both a flat vector and a named-field breakdown
- An untagged union provides no type safety at all; a
taggedunion exists specifically for when that safety matters
SystemVerilog Scheduling Semantics noted that the Active-Inactive-NBA cluster can loop if a new event lands back in Active. This article makes that concrete — what that looping actually looks like when it settles normally, and what happens on the rare occasion it doesn't.
12 min read | Intermediate Level
What You'll Learn
- What a delta cycle is, and why multi-level combinational logic needs more than one to fully settle
- Why none of this delta-cycle activity advances simulation time
- What happens when a combinational loop has no way to reach a stable state
- How to recognize the classic mistake that causes a simulation to hang at time 0
What Is a Delta Cycle?
A delta cycle is one pass through the Active-Inactive-NBA region cluster that doesn't advance simulation time. If evaluating one event causes a signal to change, and that change causes another piece of logic sensitive to it to become active, that second piece of logic gets its own delta cycle — still at the exact same time value, just one step later in an internal sequence the simulator tracks but $time never reflects.
Multi-Level Combinational Logic Needs Multiple Delta Cycles
Here, a single signal change ripples through three levels of combinational logic:
module tb;
reg a;
wire b, c, d;
assign b = a;
assign c = b;
assign d = c;
initial begin
a = 0;
#10 a = 1;
#1 $display ("[%0t] a=%b b=%b c=%b d=%b", $time, a, b, c, d);
end
endmodule
When a changes to 1 at 10ns, that change triggers assign b = a, which triggers assign c = b, which triggers assign d = c — each one its own delta cycle, cascading through all three levels of logic. All of this happens at the exact same time value, 10ns; none of it advances $time even slightly. By the time the $display runs, one full time unit later at 11ns, every level has long since settled: a=1 b=1 c=1 d=1.
Quick Check
Q: Does adding a fourth level of combinational logic (assign e = d;) require simulation time to advance any further for everything to settle?
Show Answer
No. It requires one additional delta cycle — the fourth level's own propagation — but all of that still happens at the same time value as the original change. Delta cycles scale with how many levels of logic a change has to ripple through, not with simulation time.
When the Loop Never Stops: A Combinational Feedback Loop
Delta cycles settle when each new one leads to a stable state. But a purely combinational loop with an odd number of inversions and no clocked element to break the cycle never reaches one:
module tb;
reg a;
always @ (a)
a = ~a;
initial begin
a = 0;
#10 $display ("[%0t] a=%b", $time, a);
end
endmodule
a starts at 0. That very assignment triggers the always @(a) block, since a just changed — it inverts a to 1. That change triggers the same block again — a flips back to 0. And again, and again, forever — each flip is its own delta cycle, and each one immediately triggers another, with no way to ever stabilize. Simulation time never reaches 10ns, because it never advances past the original 0ns at all. Depending on the simulator, this either hangs indefinitely with no error, or terminates with an explicit "too many iterations without advancing time" message once an internal safety limit is hit.
Quick Check
Q: Would replacing always @(a) a = ~a; with always @(posedge clk) a <= ~a; (toggling on a clock edge instead) cause the same hang?
Show Answer
No. That's an ordinary, correctly-behaving toggle flip-flop — it only changes on a clock edge, which requires simulation time to actually advance between toggles. The hang specifically comes from a change triggering itself again with no time delay anywhere in the loop, which a clocked element inherently prevents.
Where Does This Matter in Practice?
A simulation stuck at time 0 with no progress, or an explicit iteration-limit error, is one of the most common early debugging experiences in RTL design — and it's very often exactly this: an accidental combinational feedback path, sometimes through several levels of gates or a mux whose output unintentionally loops back into its own input. Recognizing "time isn't advancing at all" as the specific symptom, rather than assuming the simulator itself is broken, is the fastest way to know what to actually look for.
Common Beginner Mistakes
Mistake #1: Assuming delta cycles cost simulation time
Delta cycles never advance $time, no matter how many of them occur. Why? A long chain of combinational logic can take many delta cycles to fully settle, but as far as anything checking $time is concerned, all of that happens instantaneously, at a single time value.
Mistake #2: Assuming a stuck simulation is a tool problem
A simulation that never progresses past time 0 is far more often caused by an accidental combinational loop in the code than by an actual simulator bug. Why? As this article's second example shows, this is a direct, well-understood consequence of how delta cycles work — not a mysterious failure.
Mistake #3: Creating an odd number of inversions in a feedback loop
Any purely combinational loop with an odd number of inversions and no clocked element to break the cycle can never reach a stable state. Why? Each pass around the loop flips the value again, generating an endless sequence of delta cycles — this is exactly why real sequential logic always includes a clocked (registered) element somewhere in any feedback path.
Mistake #4: Confusing a delta-cycle hang with a slow simulation
These look similar from the outside (nothing seems to be happening) but are fundamentally different. Why? A slow simulation is still advancing $time, just gradually; a delta-cycle hang means $time is completely frozen — checking whether time is moving at all is the fastest way to tell the two apart.
Practice Exercise
Challenge: Predict a 3-Inverter Ring
Given three continuous assignments forming a ring — assign a = ~c; assign b = ~a; assign c = ~b; — would this settle to a stable state, or hang? Compare your answer to what a 2-inverter ring (assign a = ~b; assign b = ~a;) would do.
Hint
Count the total number of inversions encountered going all the way around each loop back to the starting signal — and check whether that count is odd or even.
Solution
The 3-inverter ring hangs. Going around the loop passes through 3 inversions — an odd number — so no stable fixed point exists; each full pass around the loop flips the starting value again, generating endless delta cycles, just like the single self-inverting signal in this article's main example.
The 2-inverter ring settles. It has 2 inversions — an even number — so a stable fixed point exists (in fact, two of them: a=0,b=1 or a=1,b=0). Once reached, nothing further changes, and no more delta cycles are triggered. The general rule: an odd number of inversions around a pure combinational loop never stabilizes; an even number does.
Summary
In this tutorial, you learned:
- A delta cycle is one pass through Active-Inactive-NBA that doesn't advance simulation time
- Multi-level combinational logic settles through as many delta cycles as it has levels, all at the same time value
- A purely combinational loop with an odd number of inversions and no clocked element never reaches a stable state, generating endless delta cycles instead
- A simulation stuck at time 0 with no progress is a strong, specific signal to look for an accidental combinational feedback path
- The key way to tell a delta-cycle hang apart from a merely slow simulation is whether
$timeis advancing at all
Writing out a ##1 a ##1 a to say "a should be true for 3 cycles in a row" gets unwieldy fast, especially once the count grows. SystemVerilog provides three repetition operators that express this compactly — and two of them, despite looking similar, behave in a genuinely different way that's worth understanding precisely.
13 min read | Intermediate Level
What You'll Learn
- How
[*n]compactly expresses n consecutive repetitions of the same condition - How
[->n](goto repetition) finds the nth occurrence of a condition, with gaps allowed in between - How
[=n](non-consecutive repetition) differs from goto in exactly where its match is allowed to end - Why the exact same signal trace can pass under
[=n]but fail under[->n]
Consecutive Repetition: [*n]
expr[*n] requires expr to be true for n consecutive clock cycles in a row. req2[*3] is exactly equivalent to writing req2 ##1 req2 ##1 req2 — the repetition operator just avoids spelling that out by hand:
module tb;
bit req1, req2;
bit clk;
always #10 clk = ~clk;
// Once req1 is seen, req2 must stay high for 3 consecutive
// cycles starting the very next cycle
sequence s_consec;
@(posedge clk) req1 ##1 req2[*3];
endsequence
assert property (s_consec)
$display ("[%0t] Match: req2 held high for 3 consecutive cycles", $time);
initial begin
req1 <= 1; req2 <= 0;
@(posedge clk); // 10ns: req1=1
req1 <= 0; req2 <= 1;
@(posedge clk); // 30ns: req2's 1st consecutive cycle
@(posedge clk); // 50ns: req2's 2nd consecutive cycle
@(posedge clk); // 70ns: req2's 3rd consecutive cycle - match completes
req2 <= 0;
@(posedge clk); // 90ns
#20 $finish;
end
endmodule
req1 is seen at 10ns, and req2 stays high for exactly three cycles afterward — 30ns, 50ns, and 70ns — so the sequence completes and the assertion's action block fires at 70ns, printing "Match: req2 held high for 3 consecutive cycles". Every other independent attempt starting at 30ns, 50ns, 70ns, or 90ns fails immediately, since req1 is 0 at each of those points — only the attempt that started with req1=1 at 10ns has any chance of succeeding.
Range Repetition: [*n:m] and [*n:$]
A range works the same way, just with flexible bounds instead of a fixed count:
req2[*2:4] // req2 true for anywhere between 2 and 4 consecutive cycles
req2[*2:$] // req2 true for 2 or more consecutive cycles, with no upper limit
Quick Check
Q: In the worked example above, if req2 had only stayed high for 2 cycles (30ns and 50ns) before dropping at 70ns, would req1 ##1 req2[*3] still match?
Show Answer
No. [*3] requires exactly 3 consecutive cycles — dropping after only 2 breaks the requirement, and this specific attempt fails. A range like [*2:3] would have accepted either count, but a plain [*3] does not.
Goto Repetition: [->n]
expr[->n] waits for expr to become true a total of n times — the occurrences don't need to be consecutive, gaps are allowed in between. The important detail: the sequence's own match point is fixed exactly at the cycle of the nth occurrence, with no flexibility about where that match "ends."
sequence s_goto;
@(posedge clk) a[->2] ##1 b;
endsequence
This says: wait for a to occur twice (with any gap in between), and b must be true in the cycle immediately following that 2nd occurrence — no later.
Non-Consecutive Repetition: [=n]
expr[=n] also waits for expr to become true n times with gaps allowed, but differs from goto in one specific way: its match point does not have to be exactly the nth occurrence — it can be any later cycle too, as long as expr stays false the whole way there:
sequence s_nonconsec;
@(posedge clk) a[=2] ##1 b;
endsequence
Because [=n]'s match point can slide forward through any number of additional false cycles, this is effectively evaluated as several candidate possibilities in parallel — the property succeeds overall if any valid placement makes the rest of the sequence hold true.
Comparing goto and non-consecutive on the Same Trace
Here's a trace where a occurs at cycles 1 and 3 (with a gap at cycle 2), and b doesn't show up until cycle 5, staying false at cycles 2 and 4:
| Cycle | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| a | 1 | 0 | 1 | 0 | 0 |
| b | 0 | 0 | 0 | 0 | 1 |
a[->2] ##1 b (goto): a's 2nd occurrence is at cycle 3, so the goto match ends exactly there — no flexibility. ##1 b then requires b to be true precisely at cycle 4. But b=0 at cycle 4, so this fails.
a[=2] ##1 b (non-consecutive): the match point for the [=2] portion doesn't have to be cycle 3 — it can also be cycle 4, since a stays false there. Using that later match point, ##1 b now requires b at cycle 5 instead — and b=1 there, so this passes.
This exact behavior — goto and non-consecutive repetition genuinely disagreeing on the same trace — is one of the most subtle corners of SVA syntax, and it's easy to find experienced engineers who mix the two up. If this distinction matters for a real check you're writing, it's worth verifying the exact behavior against your specific simulator rather than relying on this explanation alone, since matching semantics for repetition operators are a known area of subtlety even among production tools.
Quick Check
Q: Using the same trace, if b were high at cycle 4 instead of cycle 5, would both a[->2] ##1 b and a[=2] ##1 b pass?
Show Answer
Yes. If b is true exactly one cycle after a's 2nd occurrence (cycle 3), both the rigid goto match point and one of the non-consecutive repetition's candidate match points land on the same answer — the two operators only disagree when the correct answer specifically depends on that extra flexibility.
Where Are These Used?
[*n] is common for checking a signal holds steady for a required minimum duration — a reset pulse width, or a data-valid window. [->n] and [=n] show up in protocols where an event needs to happen a specific number of times before something else is expected, like waiting for a fixed number of acknowledge pulses across an arbitrary number of cycles before checking that a completion signal follows.
Common Beginner Mistakes
Mistake #1: Confusing [*n] with [->n]
[*n] requires consecutive cycles; [->n] allows gaps between occurrences. Why? Using [*n] when gaps are actually expected will fail the moment the condition drops even briefly — the wrong operator here doesn't just give an unexpected result, it changes what's actually being checked.
Mistake #2: Assuming goto and non-consecutive repetition are interchangeable
As the comparison trace shows, they can produce different results on the exact same signal behavior. Why? Goto rigidly anchors its match to the nth occurrence; non-consecutive repetition allows that match point to slide later through additional false cycles — picking the wrong one changes what a downstream ##1 continuation actually requires.
Mistake #3: Forgetting a range's upper bound still needs to be reachable
[*2:4] requires the repeated condition to genuinely hold for somewhere between 2 and 4 consecutive cycles. Why? If the condition drops after only 1 cycle, that's below the range's minimum, and the attempt fails — a range doesn't make the minimum optional.
Mistake #4: Overusing [=n] or [->n] when [*n] would already do the job
If the intended behavior genuinely requires consecutive cycles, reaching for the more flexible non-consecutive or goto operators adds unnecessary ambiguity. Why? The more permissive operators accept traces a consecutive check would correctly reject — use the most restrictive operator that actually matches your intended check.
Practice Exercise
Challenge: Predict a Longer Trace
Given a occurring at cycles 1, 3, and 5 (with gaps at 2 and 4), and b true only at cycle 7 (staying false at cycle 6), predict whether a[->3] ##1 b and a[=3] ##1 b each pass or fail.
Hint
a's 3rd occurrence is at cycle 5. Work out exactly which cycle each operator's match point can land on, then check what ##1 b requires from there.
Solution
a[->3] ##1 b fails. The 3rd occurrence of a is at cycle 5, so goto's match ends exactly there, requiring b at cycle 6 — but b=0 at cycle 6.
a[=3] ##1 b passes. The non-consecutive match point can slide forward to cycle 6 (since a stays false there), which then requires b at cycle 7 instead — and b=1 there. Same underlying logic as the article's own example, just one cycle further along.
Summary
In this tutorial, you learned:
[*n]requires a condition to hold true for n consecutive cycles, and[*n:m]/[*n:$]extend that to a range[->n](goto repetition) waits for the nth occurrence of a condition, allowing gaps, but ends its match exactly at that nth occurrence[=n](non-consecutive repetition) also allows gaps, but its match point can slide forward through additional cycles where the condition stays false- This flexibility means goto and non-consecutive repetition can genuinely disagree on the same trace, specifically when a later match point would succeed but the exact nth-occurrence point would not
- Always use the most restrictive operator that matches your intended check — reaching for extra flexibility you don't actually need makes a property accept traces it should reject
Every sequence and property you've seen so far compares signals against their values at whatever cycle they're checked. But some checks genuinely need to remember a value from earlier in the sequence, and compare it against something that happens later — without that, you can only ever compare against a signal's current value, which may have already moved on by the time you actually need it.
12 min read | Intermediate Level
What You'll Learn
- Why comparing against a signal's current value can silently check the wrong thing, once that signal has already changed
- How to declare and assign a local variable inside a sequence, using assignment-action syntax
- Why local variables correctly track each separate attempt independently, since a new attempt starts on every clock edge
- A canonical real use case: verifying that returned data matches the address that was actually requested
The Problem: A Signal Can Change Before You're Ready to Check It
Consider checking that acknowledged data matches the address that was requested, without any local variable:
// Without a local variable - compares against addr's CURRENT value
assert property (@(posedge clk) req ##2 (ack && data == addr));
Now suppose addr is 0x10 when req fires, but by the time ack arrives two cycles later, the bus has already moved on and addr now reads 0x20 — a completely normal thing to happen. data correctly echoes back 0x10, the address that was actually requested. But this property compares data against addr's current value at the moment of the check — 0x20, not 0x10 — so 0x10 == 0x20 is false, and the assertion reports a failure, even though the design behaved exactly as intended.
Declaring and Assigning a Local Variable
A local variable, declared inside a sequence, lets you capture a value at the moment it matters and carry it forward, immune to whatever happens to the original signal afterward:
sequence s_addr_check;
logic [7:0] captured_addr;
(req, captured_addr = addr) ##2 (ack && data == captured_addr);
endsequence
assert property (@(posedge clk) s_addr_check)
$display ("[%0t] Match: data correctly matches the originally requested address", $time);
logic [7:0] captured_addr; declares the local variable at the top of the sequence. (req, captured_addr = addr) is the key piece — the comma-separated part after req is an assignment action, executed the same cycle req is found true, locking in whatever addr was at that exact moment. Two cycles later, the consequent compares data against captured_addr — the frozen value from request time — not against addr's current value.
Comparing Both Versions on the Same Trace
Using the exact same signal trace for both properties:
| Cycle | Event |
|---|---|
| 1 | req=1, addr=0x10 |
| 2 | addr changes to 0x20 |
| 3 | ack=1, data=0x10 |
Without the local variable: at cycle 3, data == addr compares 0x10 against addr's current value, 0x20 — fails.
With the local variable: captured_addr locked in 0x10 back at cycle 1. At cycle 3, data == captured_addr compares 0x10 against 0x10 — passes, correctly recognizing that the design did exactly what it was supposed to.
Quick Check
Q: If addr had stayed at 0x10 the entire time instead of changing to 0x20, would both versions of the property produce the same result?
Show Answer
Yes. The two versions only disagree when the signal being compared changes between the moment it's captured and the moment it's checked. If addr never changes, comparing against its current value and comparing against a captured value give the identical result.
Local Variables Track Each Attempt Independently
Since a fresh attempt at a sequence starts on every single clock edge, several attempts can be in flight simultaneously — and each one gets its own independent copy of any local variable it declares. An attempt that starts at cycle 5, capturing its own addr value, doesn't interfere with a completely separate attempt that started at cycle 3 and captured a different value at that time. Each thread's local storage is entirely private to that thread.
Quick Check
Q: If a second req fired at cycle 2 (one cycle after the first, with a different address), while the cycle-1 attempt is still waiting to resolve at cycle 3, would the two attempts' captured_addr values interfere with each other?
Show Answer
No. Each attempt has its own private copy of captured_addr, tied to that specific thread — the cycle-1 attempt's captured value and the cycle-2 attempt's captured value are completely independent, even though both are in flight at the same time.
Where Are Local Variables Used?
Verifying that returned data matches a requested address is one of the most common uses, but the same pattern applies anywhere a value needs to be remembered across a multi-cycle transaction — counting how many grants occurred during a request window, or checking that a response's tag matches the tag of the request that triggered it.
Common Beginner Mistakes
Mistake #1: Comparing against a signal's current value instead of capturing it
As the first example shows, this produces a spurious failure the moment the compared signal legitimately changes between the trigger and the check. Why? If a design has any reason to move on to something else before the response arrives — which is completely normal — a check with no local variable can only ever see the signal's latest value, not the one that actually mattered.
Mistake #2: Forgetting the comma-separated assignment-action syntax
A local variable assignment is attached to a specific term using (condition, variable = expression), inside the parentheses — not as a separate statement elsewhere in the sequence. Why? This syntax ties the assignment to the exact cycle the condition is found true, which is what makes the captured value correspond to the right moment in the first place.
Mistake #3: Assuming overlapping attempts share the same local variable
Each independent attempt at a sequence gets its own private copy of any local variable it declares. Why? Assuming a shared, single copy would mean one attempt's captured value could overwrite another's, corrupting checks that are supposed to be completely independent of each other.
Mistake #4: Declaring a local variable outside the sequence or property
A local variable has to be declared inside the sequence or property block it belongs to, not as an ordinary module-level variable. Why? A module-level variable would be shared storage across every attempt, losing exactly the per-attempt independence a local variable is meant to provide.
Practice Exercise
Challenge: Capture and Compare a Transaction Tag
Write a sequence with a local variable captured_tag that captures tag the cycle req is seen, and checks that resp_tag matches it exactly 3 cycles later, when resp_valid is high.
Hint
Follow the same structure as s_addr_check — declare the local variable, attach the assignment action to the req term, and compare against the captured value in the consequent.
Solution
sequence s_tag_check;
logic [3:0] captured_tag;
(req, captured_tag = tag) ##3 (resp_valid && resp_tag == captured_tag);
endsequence
assert property (@(posedge clk) s_tag_check);
Just like the address example, this correctly validates resp_tag against the tag that was actually present when req fired — not whatever tag happens to be three cycles later, which could easily have changed if another transaction started in the meantime.
Summary
In this tutorial, you learned:
- Comparing against a signal's current value only works if that signal never changes between the trigger and the check — a local variable is needed whenever it might
- A local variable is declared inside a sequence or property, and assigned using
(condition, variable = expression)attached to a specific term - Each independent attempt at a sequence gets its own private copy of any local variable, even when several attempts are in flight simultaneously
- Verifying that a response (data, tag, or similar) matches what was actually requested is the canonical use case for this feature
SystemVerilog $rose, $fell, $stable covered detecting an edge or the absence of one. This article covers three more sampled-value system functions: $past, for reaching back further than just "the previous cycle"; $sampled, for reading a signal's assertion-visible value from procedural code; and $changed, the direct logical complement of $stable.
11 min read | Intermediate Level
What You'll Learn
- How
$pastretrieves a signal's value from a specific number of cycles ago, not just the immediately previous one - How
$past's optional gating argument skips cycles where a condition wasn't true - What
$sampledis for, and why it matters specifically inside procedural code - Why
$changedis just the logical opposite of$stable
$past: Reaching Back Further Than One Cycle
$past(expr) returns the value expr had one clock tick ago — the classic use case is checking a registered signal against the value that fed it:
// Checks that out correctly holds whatever in was one cycle earlier -
// a straightforward 1-cycle pipeline register check
assert property (@(posedge clk) out == $past(in));
Given in sampled as 5, 7, 2, 9 across four consecutive cycles, a correctly-implemented 1-cycle delay register (out <= in; every cycle) produces out values of 5, 7, 2 starting from the second cycle onward — and checking out == $past(in) passes at every one of those cycles, since each out value exactly matches what in was one cycle before it.
Now suppose the design has a bug — an off-by-one delay, lagging by 2 cycles instead of 1. At the cycle where out should show in's value from one cycle back (7), it instead still shows the value from two cycles back (5). The assertion catches this immediately: $past(in) correctly evaluates to 7, but out is 5 — a clear failure, exactly identifying the pipeline timing bug.
Looking Back More Than One Cycle
A second argument specifies how many cycles back to look:
assert property (@(posedge clk) out2 == $past(in, 2)); // 2-cycle pipeline stage
Quick Check
Q: At the very first clock edge of a simulation, what would $past(in) return?
Show Answer
The default sampled value of in — not nothing. Per the LRM, when there's no prior clock tick to look back to yet, $past falls back to the expression's default sampled value (0 for a 2-state variable, X for a 4-state one) instead of being left undefined. It's a well-defined result, just not necessarily a meaningful one — it's being compared against a value nothing ever actually drove.
Skipping Cycles With a Gating Argument
A third, optional argument gates which cycles actually count as "history" — instead of strictly N ticks ago in absolute time, $past looks back to the most recent cycle where the gating condition was true, skipping over any cycles where it wasn't:
// Compares captured against data's value from the most recent cycle
// where enable was actually high - not just literally 1 cycle ago
assert property (@(posedge clk) captured == $past(data, 1, enable));
This is useful whenever a value is only meant to update on specific qualifying cycles — without the gating argument, $past would compare against whatever data happened to be exactly one cycle back, even on a cycle where enable was low and nothing was actually supposed to be captured.
$sampled: Reading a Signal's Assertion-Visible Value
$sampled(expr) returns the same preponed-region value an assertion would use, but callable from ordinary procedural code — useful when you want a $display or other procedural statement to show exactly the value an assertion actually evaluated, rather than whatever the signal's live value happens to be at the exact point that procedural code executes:
if (some_condition)
$display ("Value seen by the assertion: %0d", $sampled(data));
Without $sampled, procedural code reading data directly could, in principle, see a value that's already moved on from what the assertion itself sampled in the preponed region — $sampled guarantees the two match.
$changed: The Opposite of $stable
$changed(expr) is true exactly when expr's value differs from its previous sampled value — the direct logical complement of $stable. Reusing the same signal trace verified in the $rose/$fell/$stable article:
| Time (ns) | a | $stable(a) | $changed(a) |
|---|---|---|---|
| 10 | 0 | PASS | FAIL |
| 30 | 1 | FAIL | PASS |
| 50 | 1 | PASS | FAIL |
| 70 | 1 | PASS | FAIL |
| 90 | 1 | PASS | FAIL |
| 110 | 1 | PASS | FAIL |
| 130 | 1 | PASS | FAIL |
| 150 | 0 | FAIL | PASS |
| 170 | 1 | FAIL | PASS |
| 190 | 1 | PASS | FAIL |
At every one of these samples, $changed(a) is exactly the opposite of $stable(a) — wherever the value held steady, $stable passes and $changed fails, and wherever it moved, the reverse.
Even at 10ns — the very first sample, with no earlier posedge yet — $stable and $changed still land on exactly opposite results. Before any real prior tick exists, both functions compare against a's default sampled value (0 for a 2-state bit) instead of being left undefined, so the same complementary relationship holds there too.
Quick Check
Q: Would assert property (@(posedge clk) !$changed(config_reg)); and assert property (@(posedge clk) $stable(config_reg)); check the same thing?
Show Answer
Yes — from the second sample onward, !$changed(x) and $stable(x) are logically identical, since $changed is defined as the exact complement of $stable. Either form expresses "this value must not change" equally well.
Where Are These Used?
$past is the standard way to verify a pipeline stage's registered output against whatever fed it some number of cycles earlier — exactly the kind of check that catches an off-by-one timing bug in a multi-stage datapath. $changed is a natural fit anywhere the condition being checked reads more naturally as "this changed" than "this failed to stay the same," even though both express the same idea.
Common Beginner Mistakes
Mistake #1: Assuming $past returns nothing at all on the very first checked edge
It actually returns a well-defined value even there — the expression's default sampled value, not an undefined result. Why? Per the LRM, when there's no prior clock tick to look back to yet, $past falls back to that default (0 for a 2-state variable, X for a 4-state one) instead of being left unusable — it just may not be a meaningful comparison yet, since nothing real has actually been registered.
Mistake #2: Assuming $past(x, N) always means "N cycles ago" when a gating argument is present
Once a gating condition is added, $past instead looks back to the Nth most recent cycle where that condition was true — not a fixed number of cycles in absolute time. Why? Mixing these two interpretations up produces a check comparing against the wrong historical value entirely, especially on a signal that doesn't update every single cycle.
Mistake #3: Reading a signal directly in procedural code when $sampled was needed
A signal's live value at the point procedural code executes isn't always guaranteed to match what an assertion sampled for that same cycle. Why? If a display statement or debug check needs to show exactly what an assertion actually evaluated, $sampled is the way to guarantee that match.
Mistake #4: Treating $changed as if it were a different check from !$stable
They're the same check, just phrased in opposite terms. Why? Writing both a $changed-based and a $stable-based assertion for what's logically the same condition is redundant — pick whichever phrasing reads more naturally for the specific property being expressed.
Practice Exercise
Challenge: Check a 3-Stage Pipeline
Write an assertion checking that stage3_out correctly holds the value data_in had exactly 3 cycles earlier.
Hint
$past's second argument specifies how many cycles back to look — this is a direct extension of the basic 1-cycle example in this article.
Solution
assert property (@(posedge clk) stage3_out == $past(data_in, 3));
This follows the exact same pattern as the article's own 1-cycle and 2-cycle examples, just extended to a 3-cycle pipeline depth — $past's second argument scales to any fixed delay a design's datapath actually has.
Summary
In this tutorial, you learned:
$past(expr)returns a signal's value from one cycle ago by default, orNcycles ago with an explicit second argument- An optional gating argument makes
$pastlook back to the most recent cycle where a condition was true, rather than a fixed number of cycles in absolute time $sampled(expr)reads a signal's assertion-visible (preponed-region) value from ordinary procedural code$changed(expr)is the exact logical complement of$stable(expr)— true whenever the value differs from its previous sample- Before a real prior sample exists, all of these functions fall back to the expression's default sampled value rather than being left undefined — a well-defined result, even if not yet a meaningful one
Quiz
No quiz questions available for this article.