A SystemVerilog structure groups several named fields, which can be of different types, into one variable that you can use as a whole or field by field. In a testbench, an unpacked structure is a convenient record, such as a packet with an address, a length and a payload. In RTL, the packed structure is the one that matters: it is a single bit vector whose fields are named slices, so it builds exactly the same wires or flip-flops as a plain vector of the same width, and only the names change.
15 min read | Intermediate Level
What You'll Learn
- How a packed structure lays out its members as one bit vector, most-significant member first, and what hardware that builds
- Why assigning one structure variable to another copies its contents, rather than sharing a reference as a class handle does
- The syntax of unpacked and packed structures, and why
typedefis used once more than one variable has the same shape - How to build fixed, dynamic and associative arrays of structures
Syntax
struct {
[list of variables]
} struct_name;
Unpacked Structures
A structure is unpacked by default, defined with the struct keyword and a list of member declarations inside curly brackets, followed by the structure's name:
Structure Example
module tb;
// Create a structure called "st_fruit"
// which to store the fruit's name, count and expiry date in days.
// Note: this structure declaration can also be placed outside the module
struct {
string fruit;
int count;
byte expiry;
} st_fruit;
initial begin
// st_fruit is a structure variable, so let's initialize it
st_fruit = '{"apple", 4, 15};
// Display the structure variable
$display ("st_fruit = %p", st_fruit);
// Change fruit to pineapple, and expiry to 7
st_fruit.fruit = "pineapple";
st_fruit.expiry = 7;
$display ("st_fruit = %p", st_fruit);
end
endmodule
Output
ncsim> run
st_fruit = '{fruit:"apple", count:4, expiry:'hf}
st_fruit = '{fruit:"pineapple", count:4, expiry:'h7}
ncsim: *W,RNQUIE: Simulation is complete.
Only fruit and expiry were reassigned in the second display — count still shows 4, its original value from the very first assignment. Each member holds its own value independently; changing one never disturbs the others.
Quick Check
Q: Why does count still show 4 in the second $display, when only .fruit and .expiry were explicitly changed?
Show Answer
Because count was never touched after its initial assignment — struct members are independent storage locations, so a value set once persists until something explicitly changes that specific member.
What is the need to typedef a structure?
Only one variable was created in the example above. If there's a need to create multiple structure variables with the same constituents, it's better to create a user-defined data type using typedef — then st_fruit becomes a data type that can be used to declare as many variables of that shape as needed:
module tb;
// Create a structure called "st_fruit"
// which to store the fruit's name, count and expiry date in days.
// Note: this structure declaration can also be placed outside the module
typedef struct {
string fruit;
int count;
byte expiry;
} st_fruit;
initial begin
// st_fruit is a data type, so we need to declare a variable of this data type
st_fruit fruit1 = '{"apple", 4, 15};
st_fruit fruit2;
// Display the structure variable
$display ("fruit1 = %p fruit2 = %p", fruit1, fruit2);
// Assign one structure variable to another and print
// Note that contents of this variable is copied into the other
fruit2 = fruit1;
$display ("fruit1 = %p fruit2 = %p", fruit1, fruit2);
// Change fruit1 to see if fruit2 is affected
fruit1.fruit = "orange";
$display ("fruit1 = %p fruit2 = %p", fruit1, fruit2);
end
endmodule
Output
ncsim> run
fruit1 = '{fruit:"apple", count:4, expiry:'hf} fruit2 = '{fruit:"", count:0, expiry:'h0}
fruit1 = '{fruit:"apple", count:4, expiry:'hf} fruit2 = '{fruit:"apple", count:4, expiry:'hf}
fruit1 = '{fruit:"orange", count:4, expiry:'hf} fruit2 = '{fruit:"apple", count:4, expiry:'hf}
ncsim: *W,RNQUIE: Simulation is complete.
fruit2 starts out with the default values for each member type — an empty string, 0, and 0. After fruit2 = fruit1;, both variables hold identical contents, because the assignment copies every field's value rather than making fruit2 point at the same data. This is confirmed by the final step: changing fruit1.fruit afterward has no effect on fruit2.fruit at all — the two are completely independent once the copy has happened.
Quick Check
Q: Structures behave this way because they're a value type. What would happen instead if st_fruit were a class rather than a struct, and fruit2 = fruit1; assigned one handle to another?
Show Answer
Both handles would then point at the exact same object, so changing fruit1.fruit afterward would also change what fruit2.fruit reports — the opposite of what this example shows. This is exactly the value-vs-reference distinction covered in SystemVerilog Class vs Struct.
Packed Structures
A packed structure subdivides a vector into fields that can be accessed as members, packed together in memory without gaps. The first member declared is the most significant, with subsequent members following in decreasing order of significance.
A structure is declared packed using the packed keyword — otherwise, it's unpacked by default.
Example
// Create a "packed" structure data type which is similar to creating
// bit [7:0] ctrl_reg;
// ctrl_reg [0] represents en
// ctrl_reg [3:1] represents cfg
// ctrl_reg [7:4] represents mode
typedef struct packed {
bit [3:0] mode;
bit [2:0] cfg;
bit en;
} st_ctrl;
module tb;
st_ctrl ctrl_reg;
initial begin
// Initialize packed structure variable
ctrl_reg = '{4'ha, 3'h5, 1};
$display ("ctrl_reg = %p", ctrl_reg);
// Change packed structure member to something else
ctrl_reg.mode = 4'h3;
$display ("ctrl_reg = %p", ctrl_reg);
// Assign a packed value to the structure variable
ctrl_reg = 8'hfa;
$display ("ctrl_reg = %p", ctrl_reg);
end
endmodule
Output
ncsim> run
ctrl_reg = '{mode:'ha, cfg:'h5, en:'h1}
ctrl_reg = '{mode:'h3, cfg:'h5, en:'h1}
ctrl_reg = '{mode:'hf, cfg:'h5, en:'h0}
ncsim: *W,RNQUIE: Simulation is complete.
Because mode occupies the top 4 bits, cfg the next 3, and en the bottom bit, assigning the raw value 8'hfa (binary 1111_1010) to the whole struct splits cleanly into mode = 4'hf, cfg = 3'h5, and en = 1'h0 — exactly what the output shows. The struct and the raw 8-bit vector are two views of the exact same bits.
Quick Check
Q: If ctrl_reg were assigned 8'b0000_0001 (only the bottom bit set), what would mode, cfg, and en each show?
Show Answer
mode = 0, cfg = 0, en = 1. Only the bottom bit is set, and that bit belongs entirely to en — the upper 7 bits, covering mode and cfg, are all zero.
What It Synthesizes Into
A packed structure is only a way of naming slices of a bit vector, so it adds no hardware of its own. The register below stores a packed cmd_t and reads its two fields by name.
module cmd_reg (
input logic clk, rst_n, load,
input logic [31:0] d,
output logic [7:0] opcode,
output logic [23:0] addr
);
typedef struct packed {
logic [7:0] opcode;
logic [23:0] addr;
} cmd_t;
cmd_t q;
always_ff @(posedge clk or negedge rst_n)
if (!rst_n) q <= '0;
else if (load) q <= d;
assign opcode = q.opcode;
assign addr = q.addr;
endmodule
Synthesis result: With the default synthesis flow of ChipVerify Lab (Yosys with the SkyWater 130 nm high-density cell library), this module builds 32 flip-flops with asynchronous reset and 32 2 to 1 multiplexers that hold the value when load is 0, 64 cells in all. The same register written as a plain logic [31:0] q, with opcode = q[31:24] and addr = q[23:0], builds exactly the same 64 cells. The field names exist only in the source code and in the waveform viewer: opcode is bits 31 to 24 because it is the first member.
Array of Structures
An array — fixed, dynamic, or associative — can hold structures just as easily as it can hold any other type:
// Define the structure
typedef struct {
int data;
string name;
} MyStruct;
module array_examples;
// 1. Fixed Array
MyStruct fixed_array[5];
// 2. Dynamic Array
MyStruct dynamic_array[];
// 3. Associative Array
MyStruct associative_array[int];
initial begin
$display("--- Fixed Array Example ---");
// Populate the fixed array
for (int i = 0; i < 5; i++) begin
fixed_array[i].data = i * 10;
fixed_array[i].name = $sformatf("Fixed_%0d", i);
$display("fixed_array[%0d]: data=%0d, name=%s", i, fixed_array[i].data, fixed_array[i].name);
end
$display("
--- Dynamic Array Example ---");
// Initialize and populate the dynamic array
dynamic_array = new[3]; // Allocate space for 3 elements
dynamic_array[0].data = 100;
dynamic_array[0].name = "Dynamic_A";
dynamic_array[1].data = 200;
dynamic_array[1].name = "Dynamic_B";
dynamic_array[2].data = 300;
dynamic_array[2].name = "Dynamic_C";
for (int i = 0; i < dynamic_array.size(); i++) begin
$display("dynamic_array[%0d]: data=%0d, name=%s", i, dynamic_array[i].data, dynamic_array[i].name);
end
$display("
--- Associative Array Example ---");
// Populate the associative array using keys
associative_array[10] = '{101, "Assoc_X"};
associative_array[25] = '{202, "Assoc_Y"};
associative_array[5] = '{303, "Assoc_Z"}; // Keys don't need to be in order
// Iterating through associative array (keys are returned in sorted order)
$display("Iterating through associative_array:");
foreach (associative_array[key]) begin
$display("associative_array[%0d]: data=%0d, name=%s", key, associative_array[key].data, associative_array[key].name);
end
end
endmodule
Output
xcelium> run --- Fixed Array Example --- fixed_array[0]: data=0, name=Fixed_0 fixed_array[1]: data=10, name=Fixed_1 fixed_array[2]: data=20, name=Fixed_2 fixed_array[3]: data=30, name=Fixed_3 fixed_array[4]: data=40, name=Fixed_4 --- Dynamic Array Example --- dynamic_array[0]: data=100, name=Dynamic_A dynamic_array[1]: data=200, name=Dynamic_B dynamic_array[2]: data=300, name=Dynamic_C --- Associative Array Example --- Iterating through associative_array: associative_array[5]: data=303, name=Assoc_Z associative_array[10]: data=101, name=Assoc_X associative_array[25]: data=202, name=Assoc_Y xmsim: *W,RNQUIE: Simulation is complete.
The three associative array keys were assigned out of order — 10, then 25, then 5 — but foreach visits them in sorted order (5, 10, 25), not insertion order. Each entry's data still correctly matches whichever key it was assigned under.
Where Is This Used?
Packed structures are the standard way to model a hardware register's bitfields with readable member names, instead of manually slicing and masking bits everywhere the register is touched. Unpacked structures — especially typedef'd ones — are commonly used for testbench transaction or packet objects that bundle several related fields together into one convenient unit.
Common Beginner Mistakes
Mistake #1: Assuming struct assignment shares a reference
As the typedef example shows, it doesn't — assigning one struct variable to another copies every field, leaving the two variables fully independent afterward. Why? This is the opposite of how assigning one class handle to another behaves — struct is a value type, class is a reference type.
Mistake #2: Forgetting the first-declared member of a packed struct is the most significant
It's easy to assume declaration order runs least-significant-first instead. Why? Getting this backward means a packed struct meant to model a real register's bitfields ends up with every field mapped to the wrong bit positions.
Mistake #3: Not accounting for cumulative width when reasoning about field positions
A packed member's exact bit position depends on the widths of every member declared before it, not just its own size. Why? Changing an earlier member's width shifts the position of every member that follows it — worth re-checking the full layout whenever a packed struct's fields change size.
Mistake #4: Assuming associative array iteration follows insertion order
As the array-of-structures example shows, keys 10, 25, and 5 were inserted in that order, but foreach visits them as 5, 10, 25. Why? Associative arrays iterate in sorted key order, regardless of the order elements were actually added.
Practice Exercise
Challenge: Decode a Packed Instruction
Given typedef struct packed { bit [2:0] opcode; bit [4:0] operand; } instr_t;, what would opcode and operand show if the whole struct were assigned 8'hA6?
Hint
opcode is declared first, so it occupies the most significant bits. Convert 0xA6 to binary and split it into the top 3 bits and the bottom 5.
Solution
opcode = 3'b101 (5), operand = 5'b00110 (6). 8'hA6 is 1010_0110 in binary — the top 3 bits (101) belong to opcode, since it's declared first, and the remaining 5 bits (00110) belong to operand.
Summary
In this tutorial, you learned:
- A structure holds members of different types, referenced as a whole or individually by name; an array holds elements that all share the same type
typedef-ing a structure turns it into a reusable data type, useful whenever more than one variable of the same shape is needed- Assigning one structure variable to another copies every field — the two variables become fully independent, unlike assigning one class handle to another
- A packed structure lays its members out as contiguous bits, with the first-declared member occupying the most significant position
- Arrays of structures work the same way as arrays of any other type, whether fixed, dynamic, or associative — and associative arrays always iterate in sorted key order
In complex testbenches, some variable declarations end up with a long data-type specification, or need to be used in multiple places throughout the code. A typedef gives a user-defined name to an existing data type, so that name can be reused everywhere afterward — avoiding the need to edit multiple places if the underlying type ever needs to change.
10 min read | Intermediate Level
What You'll Learn
- How
typedefcreates a reusable name for a data type, useful for long or repeated type specifications - Why assigning a value wider than a typedef'd type still truncates, exactly as it would for any variable of that width
- The difference between
typedef(a new name for a type) andalias(multiple names for the same physical net) - Why
aliasonly works on nets, never on variables
Typedef
// Normal declaration may turn out to be quite long
shortint unsigned my_data;
enum {RED, YELLOW, GREEN} e_light;
bit [7:0] my_byte;
// Declare an alias for this long definition
typedef shortint unsigned u_shorti;
typedef enum {RED, YELLOW, GREEN} e_light;
typedef bit [7:0] ubyte;
// Use these new data-types to create variables
u_shorti my_data;
e_light light1;
ubyte my_byte;
Syntax
typedef data_type type_name [range];
Example
module tb;
typedef shortint unsigned u_shorti;
typedef enum {RED, YELLOW, GREEN} e_light;
typedef bit [7:0] ubyte;
initial begin
u_shorti data = 32'hface_cafe;
e_light light = GREEN;
ubyte cnt = 8'hFF;
$display ("light=%s data=0x%0h cnt=%0d", light.name(), data, cnt);
end
endmodule
Output
ncsim> run light=GREEN data=0xcafe cnt=255 ncsim: *W,RNQUIE: Simulation is complete.
data shows 0xcafe, not the full 0xface_cafe that was assigned. u_shorti is typedef'd from shortint unsigned, which is only 16 bits wide — assigning a 32-bit literal to it truncates down to the lower 16 bits, exactly as it would for any ordinary 16-bit variable. A typedef only renames an existing type; it doesn't change any of that type's own behavior, including its width.
Quick Check
Q: Why does data end up as 0xcafe specifically, rather than being truncated to some other value?
Show Answer
Because truncation to a narrower width keeps the lower bits and discards the upper ones. 32'hface_cafe's lower 16 bits are cafe — that's exactly what survives once the value is forced into a 16-bit u_shorti.
Alias
An alias statement declares multiple names for the same physical net — it does not work on variables. Per IEEE 1800 §10.11 ("Net aliasing"): "Variables and hierarchical references cannot be used in alias statements." It's mainly used to model a bi-directional short-circuit connection, and can appear inside modules, interfaces, and generate blocks.
wire [7:0] data;
wire [7:0] mydata;
alias mydata = data; // "mydata" and "data" now name the same physical net
assign data = 8'hFF; // drives the shared net -- mydata reads back 8'hFF too
data and mydata are two names for the exact same physical net, so driving data is indistinguishable from driving mydata — unlike a variable, a wire is driven with a continuous assign (or force), not a plain procedural =.
Quick Check
Q: Could alias be used to give a second name to a logic variable driven procedurally inside an always block?
Show Answer
No. alias only works on nets — variables and hierarchical references are explicitly disallowed, per the IEEE 1800 citation above. A logic variable driven procedurally isn't a valid target for alias at all.
Where Is This Used?
typedef is commonly used in testbenches to give a project's own custom bit-widths — like a 21-bit address or a 4-bit opcode — a meaningful, consistent name used everywhere, so a later width change only requires editing one typedef line rather than hunting down every individual declaration. alias is far more specialized, mostly seen in low-level net modeling, such as bidirectional pad or pin connections, rather than everyday testbench code.
Common Beginner Mistakes
Mistake #1: Forgetting a typedef'd type can still be narrower than expected
As the u_shorti example shows, a typedef doesn't change the underlying type's width or behavior — only its name. Why? Assigning a wider value than the typedef'd type can hold still truncates silently, exactly as it would without the typedef at all.
Mistake #2: Trying to use alias on a variable instead of a net
As the second Quick Check shows, this is explicitly disallowed by the LRM. Why? alias exists specifically to name a physical net, not to create a second reference to a variable's storage — that's a different problem entirely, and not one alias solves.
Mistake #3: Assuming typedef and alias solve the same problem
They don't — typedef names a type, used to declare new variables; alias names an existing net, creating no new storage at all. Why? Confusing the two means reaching for the wrong construct: typedef can't connect two existing signals together, and alias can't be used to declare a new variable.
Mistake #4: Redeclaring the same typedef separately in every file that needs it
If the same custom type needs to be used across multiple files, repeating its typedef in each one risks the definitions silently drifting out of sync. Why? Declaring it once inside a shared package and importing it everywhere keeps every file working from the exact same definition.
Practice Exercise
Challenge: Predict a Truncation
Given typedef bit [11:0] u_addr; (a 12-bit type), what value would a variable of type u_addr hold if assigned 16'hABCD?
Hint
Truncation to a narrower width keeps the lower bits and discards the upper ones — the same pattern demonstrated in this article's own u_shorti example.
Solution
12'hBCD. 16'hABCD's lower 12 bits are BCD — the upper nibble (A) is discarded, since u_addr is only 12 bits wide, exactly the same truncation behavior shown for u_shorti in this article.
Summary
In this tutorial, you learned:
typedefgives a reusable name to an existing data type, useful for long specifications or types used repeatedly throughout a testbench- A typedef'd type keeps every behavior of its underlying type, including its width — assigning a wider value than it can hold still truncates silently
aliasdeclares multiple names for the same physical net, and works only on nets — never on variables or hierarchical referencestypedefandaliassolve different problems: one names a type for declaring new variables, the other names an existing net with no new storage created
An event is a static object handle used to synchronize between two or more concurrently active processes. One process triggers the event, and another process waits for it. Events can also be assigned or compared to other event variables, assigned null, and passed to queues, functions, and tasks — and this article covers a genuine race condition between the two different ways of waiting on one, which is worth understanding well before relying on events in a real testbench.
event over; // a new event is created called over
event over_again = over; // over_again becomes an alias to over
event empty = null; // event variable with no synchronization object
8 min read | Intermediate Level
What You'll Learn
- How to trigger and wait for an event using
->and either@or.triggered - The race condition that can make
@silently miss a trigger, and why.triggereddoesn't have that problem - How the non-blocking
->>trigger operator avoids that same race without needing.triggered - How to enforce a specific firing order across multiple events with
wait_order - What happens when one event variable is assigned to another while other processes are already waiting
How to Trigger and Wait for an Event
Named events are triggered using the -> or ->> operator. Processes can wait for an event using the @ operator, or by checking .triggered:
module tb;
// Create an event variable that processes can use to trigger and wait
event event_a;
// Thread1: Triggers the event using "->" operator
initial begin
#20 ->event_a;
$display ("[%0t] Thread1: triggered event_a", $time);
end
// Thread2: Waits for the event using "@" operator
initial begin
$display ("[%0t] Thread2: waiting for trigger ", $time);
@(event_a);
$display ("[%0t] Thread2: received event_a trigger ", $time);
end
// Thread3: Waits for the event using ".triggered"
initial begin
$display ("[%0t] Thread3: waiting for trigger ", $time);
wait(event_a.triggered);
$display ("[%0t] Thread3: received event_a trigger", $time);
end
endmodule
Output
ncsim> run [0] Thread2: waiting for trigger [0] Thread3: waiting for trigger [20] Thread1: triggered event_a [20] Thread2: received event_a trigger [20] Thread3: received event_a trigger ncsim: *W,RNQUIE: Simulation is complete.
Both Thread2 and Thread3 are already parked and waiting well before Thread1 triggers event_a at 20ns, so both wake up at exactly that time — here, @ and .triggered behave identically. That's not always the case, though.
What's the Difference Between @ and .triggered?
An event's triggered state persists for the entire current time step, until simulation advances. If both the wait and the trigger happen at the same simulation time, there's a race condition — and .triggered is specifically designed to avoid it. A process waiting on .triggered always unblocks, regardless of whether the wait or the trigger happened first within that time step. A process waiting with @ does not have that guarantee — it only catches a trigger if it's already actively parked waiting at the exact moment the trigger occurs:
module tb;
// Create an event variable that processes can use to trigger and wait
event event_a;
// Thread1: Triggers the event using "->" operator at 20ns
initial begin
#20 ->event_a;
$display ("[%0t] Thread1: triggered event_a", $time);
end
// Thread2: Starts waiting for the event using "@" operator at 20ns
initial begin
$display ("[%0t] Thread2: waiting for trigger ", $time);
#20 @(event_a);
$display ("[%0t] Thread2: received event_a trigger ", $time);
end
// Thread3: Starts waiting for the event using ".triggered" at 20ns
initial begin
$display ("[%0t] Thread3: waiting for trigger ", $time);
#20 wait(event_a.triggered);
$display ("[%0t] Thread3: received event_a trigger", $time);
end
endmodule
Output
ncsim> run [0] Thread2: waiting for trigger [0] Thread3: waiting for trigger [20] Thread1: triggered event_a [20] Thread3: received event_a trigger ncsim: *W,RNQUIE: Simulation is complete.
Thread2 never prints "received." Both Thread2 and Thread1 reach their key statements at the exact same simulation time, 20ns, and it comes down to scheduling order which one runs first — if Thread1's trigger fires before Thread2 has actually started its @(event_a) wait, the trigger is simply missed, since @ only catches an edge it's already watching for. Thread3 has no such problem: .triggered stays true for the rest of that same time step, so it doesn't matter which statement happened to execute first.
Quick Check
Q: In the example above, why does Thread3 still succeed even though it also only starts waiting at exactly 20ns, the same time Thread1 triggers the event?
Show Answer
Because event_a.triggered remains true for the entire 20ns time step once the trigger fires, not just for the instant it happens. Whether Thread3 checks it slightly before or slightly after Thread1's trigger within that same time step, the check still succeeds — unlike @, which only catches a trigger it's already actively parked waiting for.
Non-Blocking Trigger: ->>
There's a second way to trigger an event: the ->> operator. Where -> notifies every waiting process instantly, ->> schedules that notification for slightly later in the very same time step — specifically, the non-blocking region, the same scheduling region where <= assignments settle. That small delay is exactly what fixes the race condition from the previous section:
module tb;
// Create an event variable that processes can use to trigger and wait
event event_a;
// Thread1: Triggers the event using the non-blocking "->>" operator at 20ns
initial begin
#20 ->>event_a;
$display ("[%0t] Thread1: triggered event_a", $time);
end
// Thread2: Also starts waiting for the event using "@" at 20ns - the exact
// same race setup that made Thread2 miss the trigger with "->" earlier
initial begin
$display ("[%0t] Thread2: waiting for trigger ", $time);
#20 @(event_a);
$display ("[%0t] Thread2: received event_a trigger ", $time);
end
endmodule
This is the identical race condition from the @ vs .triggered example earlier — both processes reach their key statement at the exact same simulation time, 20ns. But this time, Thread2 does receive the trigger. Because ->> defers the actual notification to the non-blocking region, Thread2's @(event_a) has already registered itself as a waiter (which happens in the active region, earlier in the same time step) before the deferred notification ever fires — regardless of which of the two processes happened to run first.
This is what makes ->> useful for deterministic behavior when several processes are waiting on the same event: unlike ->, the outcome no longer depends on which process the simulator happens to schedule first within that time step.
Quick Check
Q: Why doesn't ->> have the same missed-trigger problem that plain -> has with @?
Show Answer
Because ->> doesn't notify waiting processes immediately — it schedules that notification for the non-blocking region, which always runs after every process's active-region code (including a process just now reaching its @(event) statement) has already executed for that time step. By the time the notification actually fires, any process that reached its wait statement in the same time step is already registered and waiting for it.
wait_order: Enforcing a Specific Order
wait_order waits for a list of events to be triggered in the given order, and takes an else branch if any of them fire out of order:
module tb;
// Declare three events that can be triggered separately
event a, b, c;
// This block triggers each event one by one
initial begin
#10 -> a;
#10 -> b;
#10 -> c;
end
// This block waits until each event is triggered in the given order
initial begin
wait_order (a,b,c)
$display ("Events were executed in the correct order");
else
$display ("Events were NOT executed in the correct order !");
end
endmodule
Output
Compiler version J-2014.12-SP1-1; Runtime version J-2014.12-SP1-1;
Events were executed in the correct order
V C S S i m u l a t i o n R e p o r t
a, b, and c fire at 10ns, 20ns, and 30ns respectively — exactly the order wait_order was told to expect, so the correct-order branch runs.
Where Is wait_order Used?
wait_order is useful for verifying a protocol handshake happens in the right sequence — for example, confirming a request is always asserted before a grant, and a grant before data is driven, flagging a violation immediately if any of those events ever fire out of sequence.
Merging Events
When one event variable is assigned to another, both variables end up pointing to the same underlying synchronization object. What happens to a process that's already waiting depends on exactly how it's waiting — the example below, and the note right after it, cover that distinction directly:
module tb;
// Create event variables
event event_a, event_b;
initial begin
fork
// Thread1: waits for event_a to be triggered
begin
wait(event_a.triggered);
$display ("[%0t] Thread1: Wait for event_a is over", $time);
end
// Thread2: waits for event_b to be triggered
begin
wait(event_b.triggered);
$display ("[%0t] Thread2: Wait for event_b is over", $time);
end
// Thread3: triggers event_a at 20ns
#20 ->event_a;
// Thread4: triggers event_b at 30ns
#30 ->event_b;
// Thread5: Assigns event_b to event_a at 10ns
begin
// Comment code below and try again to see Thread2 finish later
#10 event_b = event_a;
end
join
end
endmodule
Output
ncsim> run [20] Thread1: Wait for event_a is over [20] Thread2: Wait for event_b is over ncsim: *W,RNQUIE: Simulation is complete.
Thread2 starts out waiting on the original event_b object at 0ns. At 10ns, Thread5 reassigns event_b to point to the same underlying object as event_a. Because wait(event_b.triggered) checks whatever object event_b currently refers to, not a snapshot taken when the wait began, Thread2 ends up tied to event_a's trigger instead — finishing at 20ns right alongside Thread1, rather than waiting until 30ns for Thread4's separate trigger on the now-orphaned original event_b. This redirection is specific to wait(event.triggered), though — a process already blocked on @event_b at the moment of the reassignment would instead be permanently orphaned on the old synchronization object and never unblock at all, since @ binds to one specific object the moment the wait begins rather than re-checking what the variable currently points to.
Quick Check
Q: If Thread5's reassignment (event_b = event_a;) were removed entirely, at what time would Thread2 finish?
Show Answer
30ns. Without the reassignment, event_b stays its own separate object, and only Thread4's ->event_b at 30ns would trigger it — Thread2 would have no reason to finish any earlier.
Common Beginner Mistakes
Mistake #1: Using @ when a wait and a trigger might race
As the race condition example shows, @ only catches a trigger if the process is already actively parked waiting for it at that exact moment. Why? If there's any chance the wait and the trigger could land on the same simulation time, wait(event.triggered) or a ->> trigger is the safer choice — neither depends on which one happens to execute first.
Mistake #2: Assuming -> and ->> are interchangeable
-> notifies waiting processes instantly; ->> defers that notification to the non-blocking region of the same time step. Why? Code that depends on the trigger's side effects happening immediately — before the very next statement runs — can behave differently with ->>, since anything waiting on that event won't actually wake up until slightly later in that same time step.
Mistake #3: Assuming event assignment makes an independent copy
event_b = event_a; doesn't give event_b its own separate copy of anything — it makes event_b point to the exact same synchronization object as event_a. Why? A process already waiting via wait(event.triggered) picks up the new binding and ends up affected by whichever event fires next — but a process already blocked on @event_b at the moment of reassignment is orphaned on the old object instead, and never unblocks at all. Which form of waiting is in use matters here, not just whether a reassignment happened.
Mistake #4: Checking .triggered outside the time step it fired in
.triggered only stays true for the remainder of the time step the trigger occurred in. Why? Once simulation advances to a new time step, checking .triggered again correctly returns false — it's not a persistent flag that stays set until manually cleared, so code that assumes it remains true indefinitely will behave unexpectedly on a later check.
Practice Exercise
Challenge: Verify a Two-Step Handshake
Using wait_order, write a check that a req event always fires before a gnt event. Trigger gnt first at 15ns and req second at 25ns, and confirm the check correctly reports the out-of-order violation.
Hint
Follow the same wait_order (event1, event2) ... else ... pattern shown earlier, just with two events instead of three, and trigger them in the wrong order on purpose.
Solution
module tb;
event req, gnt;
initial begin
#15 -> gnt; // fires first, out of order
#10 -> req; // fires second
end
initial begin
wait_order (req, gnt)
$display ("req then gnt - correct order");
else
$display ("Violation: gnt fired before req!");
end
endmodule
Since gnt actually fires at 15ns, before req fires at 25ns, wait_order (req, gnt) detects the mismatch against the order it was told to expect and takes the else branch, reporting the violation.
Summary
In this tutorial, you learned:
- An event synchronizes two or more processes — one triggers with
->, another waits with@orwait(event.triggered) .triggeredstays true for the entire time step it fired in, so it always unblocks a waiting process regardless of execution order;@can miss a trigger if it isn't already actively waiting at that exact moment->>triggers non-blockingly, deferring notification to the non-blocking region of the same time step — which fixes the same race@is vulnerable to, without needing.triggeredwait_orderchecks that a list of events fire in a specific sequence, and branches into anelseclause if they don't- Assigning one event variable to another merges them into the same underlying synchronization object — a process already waiting via
wait(event.triggered)picks up the new binding, but a process already blocked on@eventis permanently orphaned on the old object instead - Events can be compared, aliased, set to
null, and passed to functions and tasks like any other handle
Continuing the Interprocess Communication Chapter
Continue with SystemVerilog Semaphore for controlling access to a shared resource, and SystemVerilog Mailbox for passing data between components.
An enumerated type defines a set of named values. In the following example, light_* is an enumerated variable that can store one of three possible values (0, 1, 2). By default, the first name in the list gets the value 0, and the following names get incremental values:
enum {RED, YELLOW, GREEN} light_1; // int type; RED = 0, YELLOW = 1, GREEN = 2
enum bit[1:0] {RED, YELLOW, GREEN} light_2; // bit type; RED = 0, YELLOW = 1, GREEN = 2
16 min read | Intermediate Level
What You'll Learn
- How enum values are assigned by default, and what happens when explicit and implicit assignments are mixed
- Why an enum's underlying type must be wide enough to hold every distinct value it needs
- The full range-declaration syntax (
name[N],name[N]=C,name[N:M],name[N:M]=C) and how each one differs - The built-in iteration methods (
first/last/next/prev/num/name), and whynext()/prev()move in declaration order - Why enums are strongly typed, and what happens when that's violated
Basic Enum Declaration
Any integer value can be assigned to any enumerated name. If a name has no assigned value, it automatically takes the incremented value of the previous name:
enum {RED=3, YELLOW, GREEN} light_3; // RED = 3, YELLOW = 4, GREEN = 5
enum {RED = 4, YELLOW = 9, GREEN} light_4; // RED = 4, YELLOW = 9, GREEN = 10 (automatically assigned)
enum {RED = 2, YELLOW, GREEN = 3} light_5; // Error : YELLOW and GREEN are both assigned 3
enum bit[0:0] {RED, YELLOW, GREEN} light_6; // Error: minimum 2 bits are required
light_5 fails because YELLOW auto-increments to 3 from RED's explicit value of 2, colliding with GREEN's own explicit value of 3 — every value within one enum must be unique. light_6 fails for a different reason: bit[0:0] can only hold 2 distinct values (0 and 1), but three enum members need three.
An enumeration name also can't start with a number:
enum {1WAY, 2TIMES, SIXPACK=6} e_formula; // Compilation error on 1WAY, 2TIMES
enum {ONEWAY, TIMES2, SIXPACK=6} e_formula; // Correct way is to keep the first character non-numeric
Quick Check
Q: Would enum {A=5, B, C=5} compile?
Show Answer
No. B auto-increments to 6 from A's explicit value of 5, but C is explicitly set to 5 — directly duplicating A's value. This is the same class of error as light_5 above.
Defining a Custom Enumerated Type With typedef
A custom data type can be created so the same type can be reused to declare other variables:
module tb;
// "e_true_false" is a new data-type with two valid values: TRUE and FALSE
typedef enum {TRUE, FALSE} e_true_false;
initial begin
// Declare a variable of type "e_true_false" that can store TRUE or FALSE
e_true_false answer;
// Assign TRUE/FALSE to the enumerated variable
answer = TRUE;
// Display string value of the variable
$display ("answer = %s", answer.name);
end
endmodule
Output
ncsim> run answer = TRUE ncsim: *W,RNQUIE: Simulation is complete.
Why Do We Need Enumeration?
To make code simpler and more readable. Consider the following without enumeration:
bit [1:0] light;
light = 2'b00; // Assume 00 stands for RED
// After many lines of code we have to correlate what
// 00 stands for - is it RED, YELLOW or GREEN ?
if (light == 2'b00)
// Do something
The following is more readable, thanks to the named values RED, YELLOW, and GREEN:
typedef enum {RED, YELLOW, GREEN} e_light;
e_light light;
light = RED; // Initialize light to RED
// Even after many lines of code it's easier to understand
if (light == RED)
// Do something
Enumerated-Type Ranges
| Form | Effect |
|---|---|
name | The next number will be associated with name |
name = C | Associates the constant C to name |
name[N] | Generates N named constants: name0, name1, ..., nameN-1 |
name[N] = C | The first named constant gets value C, and subsequent ones get consecutive values |
name[N:M] | The first named constant will be nameN and the last nameM, where N and M are integers |
name[N:M] = C | The first named constant, nameN, gets C, and subsequent ones get consecutive values up to nameM |
Example
module tb;
// name : The next number will be associated with name starting from 0
// GREEN = 0, YELLOW = 1, RED = 2, BLUE = 3
typedef enum {GREEN, YELLOW, RED, BLUE} color_set_1;
// name = C : Associates the constant C to name
// MAGENTA = 2, VIOLET = 7, PURPLE = 8, PINK = 9
typedef enum {MAGENTA=2, VIOLET=7, PURPLE, PINK} color_set_2;
// name[N] : Generates N named constants : name0, name1, ..., nameN-1
// BLACK0 = 0, BLACK1 = 1, BLACK2 = 2, BLACK3 = 3
typedef enum {BLACK[4]} color_set_3;
// name[N] = C : First named constant gets value C and subsequent ones
// are associated to consecutive values
// RED0 = 5, RED1 = 6, RED2 = 7
typedef enum {RED[3] = 5} color_set_4;
// name[N:M] : First named constant will be nameN and last named
// constant nameM, where N and M are integers
// YELLOW3 = 0, YELLOW4 = 1, YELLOW5 = 2
typedef enum {YELLOW[3:5]} color_set_5;
// name[N:M] = C : First named constant, nameN will get C and
// subsequent ones are associated to consecutive values until nameM
// WHITE3 = 4, WHITE4 = 5, WHITE5 = 6
typedef enum {WHITE[3:5] = 4} color_set_6;
initial begin
// Create new variables for each enumeration style
color_set_1 color1;
color_set_2 color2;
color_set_3 color3;
color_set_4 color4;
color_set_5 color5;
color_set_6 color6;
color1 = YELLOW; $display ("color1 = %0d, name = %s", color1, color1.name());
color2 = PURPLE; $display ("color2 = %0d, name = %s", color2, color2.name());
color3 = BLACK3; $display ("color3 = %0d, name = %s", color3, color3.name());
color4 = RED1; $display ("color4 = %0d, name = %s", color4, color4.name());
color5 = YELLOW3;$display ("color5 = %0d, name = %s", color5, color5.name());
color6 = WHITE4; $display ("color6 = %0d, name = %s", color6, color6.name());
end
endmodule
Output
ncsim> run color1 = 1, name = YELLOW color2 = 8, name = PURPLE color3 = 3, name = BLACK3 color4 = 6, name = RED1 color5 = 0, name = YELLOW3 color6 = 5, name = WHITE4 ncsim: *W,RNQUIE: Simulation is complete.
In name[N:M], N and M only control the suffix numbers attached to each generated name — they say nothing about the actual enum value each one holds. YELLOW[3:5] generates YELLOW3, YELLOW4, YELLOW5, but their values still start counting from 0 (since nothing precedes them in that specific enum), landing on 0, 1, 2 — not 3, 4, 5. Only adding an explicit = C, as color_set_6 does, controls the starting value directly.
Quick Check
Q: Given typedef enum {CYAN[2:4]=10} c_set;, what value would CYAN3 hold?
Show Answer
11. CYAN2 (the first one) gets the explicit value 10, and each subsequent name increments by one — CYAN3 is 11, CYAN4 is 12.
Enumerated-Type Methods
SystemVerilog includes a set of specialized methods for iterating over the values of enumerated types.
| Method | Signature | Description |
|---|---|---|
first() | function enum first(); | Returns the value of the first member of the enumeration |
last() | function enum last(); | Returns the value of the last member of the enumeration |
next() | function enum next (int unsigned N = 1); | Returns the Nth next enumeration value starting from the current value |
prev() | function enum prev (int unsigned N = 1); | Returns the Nth previous enumeration value starting from the current value |
num() | function int num(); | Returns the number of elements in the enumeration |
name() | function string name(); | Returns the string representation of the given enumeration value |
Enumeration Methods Example
// GREEN = 0, YELLOW = 1, RED = 2, BLUE = 3
typedef enum {GREEN, YELLOW, RED, BLUE} colors;
module tb;
initial begin
colors color;
// Assign current value of color to YELLOW
color = YELLOW;
$display ("color.first() = %0d", color.first()); // First value is GREEN = 0
$display ("color.last() = %0d", color.last()); // Last value is BLUE = 3
$display ("color.next() = %0d", color.next()); // Next value is RED = 2
$display ("color.prev() = %0d", color.prev()); // Previous value is GREEN = 0
$display ("color.num() = %0d", color.num()); // Total number of enum = 4
$display ("color.name() = %s" , color.name()); // Name of the current enum
end
endmodule
Output
ncsim> run color.first() = 0 color.last() = 3 color.next() = 2 color.prev() = 0 color.num() = 4 color.name() = YELLOW ncsim: *W,RNQUIE: Simulation is complete.
next() and prev() move based on declaration order, not numeric value — here they happen to coincide, since colors was declared with plain sequential values. For an enum with custom, non-sequential values, they'd diverge.
Quick Check
Q: If colors were instead declared as typedef enum {GREEN=5, YELLOW=1, RED=9, BLUE=2} colors;, and color = YELLOW, what would color.next() return?
Show Answer
RED, with value 9 — because RED is declared immediately after YELLOW in the source, regardless of the fact that 9 isn't simply "YELLOW's value (1) plus one." next() always follows declaration order, not numeric adjacency.
Type Checking
Enumerated types are strongly typed, so a variable of type enum can't be assigned an integer value outside the enumeration set unless an explicit cast is used:
typedef enum bit [1:0] {RED, YELLOW, GREEN} e_light;
module tb;
e_light light;
initial begin
light = GREEN;
$display ("light = %s", light.name());
// Invalid because of strict typing rules
light = 0;
$display ("light = %s", light.name());
// OK when explicitly cast
light = e_light'(1);
$display ("light = %s", light.name());
// OK. light is auto-cast to integer
if (light == RED | light == 2)
$display ("light is now %s", light.name());
end
endmodule
Behavior on the invalid assignment (light = 0;) varies by simulator. Aldec Riviera Pro treats it as a hard compile error:
ERROR VCP2694 "Assignment to enum variable from expression of different type." "testbench.sv" 11 1 FAILURE "Compile failure 1 Errors 0 Warnings Analysis time: 0[s]."
Cadence's ncsim only warns, and lets simulation proceed:
light = 0; | ncvlog: *W,ENUMERR (testbench.sv,11|11): This assignment is a violation of SystemVerilog strong typing rules for enumeration datatypes. Loading snapshot worklib.tb:sv .................... Done ncsim> run light = GREEN light = RED light = YELLOW ncsim: *W,RNQUIE: Simulation is complete.
Only three lines of output appear, not four — the final if statement's own $display never fires. By that point, light holds YELLOW (value 1, from the explicit cast just before it), which matches neither RED (0) nor the literal 2, so the condition is false and nothing prints for it. The comment "light is auto-cast to integer" describes why the comparison itself is legal syntax — not a claim that this particular condition happens to be true.
Where Is This Used?
Enums are the standard way to represent FSM states, opcodes, and protocol command types in both design and testbench code — named symbolic values are far more readable in waveforms and logs than raw numeric encodings, and strict typing catches an entire class of "accidentally assigned an out-of-range value" bugs at compile time that a plain bit-vector would never catch.
What It Synthesizes Into
An enumerated type used for FSM states becomes a state register, and the names exist only for the people reading the code and the waveforms. The base type decides how wide that register is, which can matter more than you might expect. The FSM below was synthesized twice: once with the line exactly as shown, and once with typedef enum logic [1:0].
module handshake (
input logic clk, rst_n, start, ack,
output logic req, done
);
typedef enum {IDLE, REQ, WAIT, DONE} state_t;
state_t state, next;
always_ff @(posedge clk or negedge rst_n)
if (!rst_n) state <= IDLE;
else state <= next;
always_comb begin
next = state;
case (state)
IDLE: if (start) next = REQ;
REQ: next = WAIT;
WAIT: if (ack) next = DONE;
DONE: next = IDLE;
endcase
end
assign req = (state == REQ) || (state == WAIT);
assign done = (state == DONE);
endmodule
Synthesis result: With the default synthesis flow of ChipVerify Lab (Yosys with the SkyWater 130 nm high-density cell library), the version with the explicit 2-bit base type builds 2 flip-flops and 6 logic cells, 8 cells in all. The version shown, with the default int base type, builds 3 flip-flops and 10 logic cells, 13 in all. Four states need only 2 bits, and the upper 30 bits of the int state register always hold 0, but the tool cannot prove that from the code. It keeps one flip-flop for those bits (they all have identical logic, so they merge into one), plus the extra gates that include that flip-flop in the next-state and output logic. Giving the enum an explicit base type, such as logic [1:0], tells the tool the real width.
Common Beginner Mistakes
Mistake #1: Assuming an enum's underlying type auto-widens to fit its members
As light_6 shows, an explicitly narrow base type (like bit[0:0]) that can't hold every distinct value needed is a compile error, not something the compiler silently widens for you. Why? Always make sure an explicitly-chosen base type is wide enough for however many distinct values the enum actually needs.
Mistake #2: Mixing implicit and explicit values without checking for collisions
As light_5 and the Quick Check above show, an auto-incremented value can silently collide with a later explicit one. Why? Whenever both styles appear in the same enum, it's worth double-checking that no auto-incremented name ends up duplicating an explicitly-assigned one.
Mistake #3: Assuming next()/prev() follow numeric order
As the second Quick Check shows, they follow declaration order instead — which only coincides with numeric order when the enum's values happen to be sequential. Why? For an enum with custom, non-sequential values, assuming numeric adjacency will give the wrong answer.
Mistake #4: Assigning a plain integer literal to an enum variable without a cast
This violates strict typing rules, and different simulators handle it differently — a hard compile error on some, a warning-but-proceeds on others. Why? Relying on this behavior means the exact same code could fail to compile on one tool while running fine on another — always use an explicit cast (e_light'(value)) when a raw integer genuinely needs to become an enum value.
Practice Exercise
Challenge: Predict a Range Declaration
Given typedef enum {CYAN[4:6] = 20} c_set;, what values do CYAN4, CYAN5, and CYAN6 each hold?
Hint
The first name in the range gets the explicit value directly; each subsequent one increments by one from there — the same pattern as color_set_6 in this article's own example.
Solution
CYAN4 = 20, CYAN5 = 21, CYAN6 = 22. The suffix numbers (4, 5, 6) only determine the generated names — the explicit = 20 sets where the actual values start counting from, exactly as WHITE[3:5] = 4 did earlier in this article.
Summary
In this tutorial, you learned:
- Enum values default to incrementing from 0, but any name can be given an explicit value, and unassigned names auto-increment from whatever came before
- An enum's underlying type must be wide enough to hold every distinct value it needs — the compiler won't widen it automatically
name[N:M]'s suffix numbers control only the generated names, not the actual values, which still start from 0 unless an explicit= Cis also givennext()andprev()move based on declaration order, not numeric value order- Enums are strongly typed — assigning a raw integer without an explicit cast violates that typing, with behavior that varies by simulator
Verilog has no dedicated text type - storing something like a test name or a log message means packing ASCII characters into a fixed-width reg vector and hoping it's wide enough. SystemVerilog fixes this with a real string data type: dynamically sized, easy to compare and slice, and built specifically for the kind of text handling a testbench needs constantly.
8 min read | Beginner Level
What You'll Learn
- What the
stringdata type is and how it differs from packing characters into areg - The operators and built-in methods available on
stringvariables - Why
stringis verification-only, unlike the fixed-width vector workaround - How to convert between strings and numeric types
What is a SystemVerilog string ?
The string data type is an ordered collection of characters. The length of a string variable is the number of characters it holds, which can change dynamically over the course of a simulation. A string variable doesn't behave the same way as a string literal, and no truncation occurs when you use the string type.
Syntax
string variable_name [= initial_value];
variable_name is a valid identifier, and the optional initial_value can be a string literal, the value "" for an empty string, or a string-typed expression. If no initial value is given at declaration, the variable defaults to "", an empty string.
SystemVerilog String Example
module tb;
// Declare a string variable called "dialog" to store string literals
// Initialize the variable to "Hello!"
string dialog = "Hello!";
initial begin
// Display the string using %s string format
$display ("%s", dialog);
// Iterate through the string variable to identify individual characters and print
foreach (dialog[i]) begin
$display ("%s", dialog[i]);
end
end
endmodule
ncsim> run Hello! H e l l o ! ncsim: *W,RNQUIE: Simulation is complete.
How are strings represented in Verilog ?
A single ASCII character requires 8 bits (1 byte), so storing a string in plain Verilog needs as many bytes as there are characters.
Click here to learn about Verilog Arrays
reg [16*8-1:0] my_string; // Can store 16 characters
my_string = "How are you"; // 5 zeros are padded from MSB, and 11 char are stored
my_string = "How are you doing?"; // 18 characters; my_string will get "w are you doing?"
Design vs. Verification: A fixed-width reg vector like my_string above is synthesizable - it maps directly to hardware bits. The string data type is not. It's a verification-only construct that exists purely for testbench code and can never appear in synthesizable RTL.
Quick Check
Q: Why does assigning "How are you doing?" (18 characters) to a 16-character-wide my_string result in "w are you doing?" instead of an error?
Show Answer
A fixed-width vector can't grow to fit the string, so the assignment silently keeps only the rightmost 16 characters and drops the first 2 ("H" and "o") from the front. This kind of silent truncation is exactly what the string type avoids.
String Operators
| Category | Operator | Semantics |
|---|---|---|
| Equality | Str1 == Str2 | Returns 1 if the two strings are equal and 0 if they are not |
| Inequality | Str1 != Str2 | Returns 1 if the two strings are not equal and 0 if they are |
| Comparison | Str1 < Str2, Str1 <= Str2, Str1 > Str2, Str1 >= Str2 | Returns 1 if the corresponding condition is true and 0 if false |
| Concatenation | {Str1, Str2, ..., StrN} | All strings are concatenated into one resultant string |
| Replication | {multiplier{Str}} | Replicates the string N times, where N is the multiplier |
| Indexing | Str[index] | Returns a byte - the ASCII code at the given index. Returns 0 if the index is out of range |
| Methods | Str.method([args]) | The dot (.) operator is used to call string functions |
Example
module tb;
string firstname = "Joey";
string lastname = "Tribbiani";
initial begin
// String Equality : Check if firstname equals or not equals lastname
if (firstname == lastname)
$display ("firstname=%s is EQUAL to lastname=%s", firstname, lastname);
if (firstname != lastname)
$display ("firstname=%s is NOT EQUAL to lastname=%s", firstname, lastname);
// String comparison : "<" compares lexicographically by ASCII value, not by length
if (firstname < lastname)
$display ("firstname=%s is LESS THAN lastname=%s", firstname, lastname);
// String comparison : ">" compares lexicographically by ASCII value, not by length
if (firstname > lastname)
$display ("firstname=%s is GREATER THAN lastname=%s", firstname, lastname);
// String concatenation : Join first and last names into a single string
$display ("Full Name = %s", {firstname, " ", lastname});
// String Replication
$display ("%s", {3{firstname}});
// String Indexing : Get the ASCII character at index number 2 of both first and last names
$display ("firstname[2]=%s lastname[2]=%s", firstname[2], lastname[2]);
end
endmodule
ncsim> run firstname=Joey is NOT EQUAL to lastname=Tribbiani firstname=Joey is LESS THAN lastname=Tribbiani Full Name = Joey Tribbiani JoeyJoeyJoey firstname[2]=e lastname[2]=i ncsim: *W,RNQUIE: Simulation is complete.
String comparison is lexicographic, based on ASCII values - "Joey" < "Tribbiani" because 'J' (ASCII 74) comes before 'T' (ASCII 84), the same way you'd compare words alphabetically.
Basic String Methods
SystemVerilog also includes a number of special methods to work with strings, using built-in method notation.
| Usage | Definition | Comments |
|---|---|---|
| str.len() | function int len() | Returns the number of characters in the string |
| str.putc() | function void putc (int i, byte c); | Replaces the ith character in the string with the given character |
| str.getc() | function byte getc (int i); | Returns the ASCII code of the ith character in str |
| str.tolower() | function string tolower(); | Returns a string with characters in str converted to lowercase |
| str.compare(s) | function int compare (string s); | Compares str and s, as in the ANSI C strcmp function |
| str.icompare(s) | function int icompare (string s); | Compares str and s, ignoring case |
| str.substr (i, j) | function string substr (int i, int j); | Returns a new string formed by the characters in position i through j of str |
Example
module tb;
string str = "Hello World!";
initial begin
string tmp;
// Print length of string "str"
$display ("str.len() = %0d", str.len());
// Assign to tmp variable and put char "d" at index 3
tmp = str;
tmp.putc (3,"d");
$display ("str.putc(3, d) = %s", tmp);
// Get the character at index 2
$display ("str.getc(2) = %s (%0d)", str.getc(2), str.getc(2));
// Convert all characters to lower case
$display ("str.tolower() = %s", str.tolower());
// Comparison
tmp = "Hello World!";
$display ("[tmp,str are same] str.compare(tmp) = %0d", str.compare(tmp));
tmp = "How are you ?";
$display ("[tmp,str are diff] str.compare(tmp) = %0d", str.compare(tmp));
// Ignore case comparison
tmp = "hello world!";
$display ("[tmp is in lowercase] str.icompare(tmp) = %0d", str.icompare(tmp));
tmp = "Hello World!";
$display ("[tmp,str are same] str.compare(tmp) = %0d", str.compare(tmp));
// Extract new string from i to j
$display ("str.substr(4,8) = %s", str.substr (4,8));
end
endmodule
str.len() = 12 str.putc(3, d) = Heldo World! str.getc(2) = l (108) str.tolower() = hello world! [tmp,str are same] str.compare(tmp) = 0 [tmp,str are diff] str.compare(tmp) = -1 [tmp is in lowercase] str.icompare(tmp) = 0 [tmp,str are same] str.compare(tmp) = 0 str.substr(4,8) = o Wor
Common Mistake: str.compare() mirrors ANSI C's strcmp - it returns 0 for equal strings and a nonzero value otherwise, not a boolean 1/0. Don't treat a nonzero result as "true" the way you might with ==.
String Conversion Methods
| Method | Definition | Description |
|---|---|---|
| str.atoi() | function integer atoi(); | Returns the integer corresponding to the ASCII decimal representation in str |
| str.atohex() | function integer atohex(); | Interprets the string as hexadecimal |
| str.atooct() | function integer atooct(); | Interprets the string as octal |
| str.atobin() | function integer atobin(); | Interprets the string as binary |
| str.atoreal() | function real atoreal(); | Returns the real number corresponding to the ASCII decimal representation in str |
| str.itoa(i) | function void itoa (integer i); | Stores the ASCII decimal representation of i into str |
| str.hextoa(i) | function void hextoa (integer i); | Stores the ASCII hexadecimal representation of i into str |
| str.octtoa(i) | function void octtoa (integer i); | Stores the ASCII octal representation of i into str |
| str.bintoa(i) | function void bintoa (integer i); | Stores the ASCII binary representation of i into str |
| str.realtoa(r) | function void realtoa (real r); | Stores the ASCII real representation of r into str |
Where Are Strings Used?
Testbenches use string constantly - test names passed via +UVM_TESTNAME, log and error messages built with $sformatf, config file paths, and comparing a DUT's ASCII output against an expected string in a reference model. None of this could be done cleanly with a fixed-width reg vector.
Common Beginner Mistakes
Mistake #1: Assuming string can be used in synthesizable RTL.
string is verification-only. If you need text-like storage in a real design, you're back to a fixed-width reg/logic vector, with the truncation behavior shown earlier.
Mistake #2: Off-by-one errors with string indexing.
Like arrays, string indexing is 0-based. firstname[2] is the third character, not the second - easy to miscount when a string is short.
Mistake #3: Treating str.compare()'s return value as a boolean.
It returns 0 for equality and a nonzero value otherwise, matching ANSI C's strcmp - not a straightforward 1-for-true result.
Practice Exercise
Challenge: Extract a Substring
Given string str = "SystemVerilog";, write a single line using str.substr() that extracts just the word "Verilog".
Hint
Index positions are 0-based. Count characters starting from 0 to find where "Verilog" begins and ends within "SystemVerilog".
Solution
str.substr(6,12)
"SystemVerilog" has "System" occupying indices 0-5, so "Verilog" starts at index 6 and ends at index 12 (the last character, "g").
Summary
In this tutorial, you learned:
- The
stringdata type is a dynamically-sized, verification-only text type - unlike a fixed-widthregvector, it never silently truncates - Strings support equality, comparison, concatenation, replication, and indexing operators
- Built-in methods like
len(),putc(),getc(),tolower(),compare(), andsubstr()cover most everyday string manipulation - Conversion methods like
atoi()anditoa()move data between string and numeric representations
Quiz
No quiz questions available for this article.