The inside keyword checks whether a given value lies within a range or set of values specified using the inside phrase. It can be used inside if and other conditional statements, in addition to being used directly as a constraint.
10 min read | Intermediate Level
What You'll Learn
- The syntax for
inside, using both explicit value lists and ranges - How
insideworks identically inside conditional statements and inside constraints - How to invert
insideto exclude a range instead of restricting to it - A practical memory-partitioning example using
insideto keep a randomized address within a specific region
Syntax
inside {}
// Inverted "inside"
!( inside {})
For example:
m_var inside {4, 7, 9} // Check if m_var is either 4, 7, or 9
m_var inside {[10:100]} // Check if m_var is between 10 and 100 inclusive
When Used in Conditional Statements
Here, inside is used both in a ternary operator and an if/else statement. flag is set to 1 if the randomized value of m_data lies within 4 to 9 (inclusive); otherwise it's set to 0. The if/else block uses the same check to print a matching message:
module tb;
bit [3:0] m_data;
bit flag;
initial begin
for (int i = 0; i < 10; i++) begin
m_data = $random;
// Used in a ternary operator
flag = m_data inside {[4:9]} ? 1 : 0;
// Used with "if-else" operators
if (m_data inside {[4:9]})
$display ("m_data=%0d INSIDE [4:9], flag=%0d", m_data, flag);
else
$display ("m_data=%0d outside [4:9], flag=%0d", m_data, flag);
end
end
endmodule
Output
ncsim> run m_data=4 INSIDE [4:9], flag=1 m_data=1 outside [4:9], flag=0 m_data=9 INSIDE [4:9], flag=1 m_data=3 outside [4:9], flag=0 m_data=13 outside [4:9], flag=0 m_data=13 outside [4:9], flag=0 m_data=5 INSIDE [4:9], flag=1 m_data=2 outside [4:9], flag=0 m_data=1 outside [4:9], flag=0 m_data=13 outside [4:9], flag=0 ncsim: *W,RNQUIE: Simulation is complete.
Every row is consistent: flag is 1 exactly when m_data falls between 4 and 9, and 0 otherwise — including the boundary values 4 and 9 themselves, both correctly counted as inside the range.
Quick Check
Q: Would m_data inside {[4:9]} be true for m_data = 9?
Show Answer
Yes. A range written as [4:9] is inclusive on both ends — 4 and 9 are both valid members of the range, not just the values strictly between them.
Used in Constraints
The inside operator is quite useful in constraints, making code shorter and more readable:
class ABC;
rand bit [3:0] m_var;
// Constrain m_var to be either 3,4,5,6 or 7
constraint c_var { m_var inside {[3:7]}; }
endclass
module tb;
initial begin
ABC abc = new();
repeat (5) begin
abc.randomize();
$display("abc.m_var = %0d", abc.m_var);
end
end
endmodule
Output
ncsim> run abc.m_var = 7 abc.m_var = 6 abc.m_var = 6 abc.m_var = 3 abc.m_var = 4 ncsim: *W,RNQUIE: Simulation is complete.
Every value of m_var falls inside the given range, [3:7].
Inverted inside
The opposite of what inside checks for can be achieved by placing ! in front of it — applicable to both constraints and conditional statements. This example is the same as the one above, except the constraint has been tweaked to reflect an inverted inside:
class ABC;
rand bit [3:0] m_var;
// Inverted inside: Constrain m_var to be outside 3 to 7
constraint c_var { !(m_var inside {[3:7]}); }
endclass
module tb;
initial begin
ABC abc = new();
repeat (5) begin
abc.randomize();
$display("abc.m_var = %0d", abc.m_var);
end
end
endmodule
Output
ncsim> run abc.m_var = 1 abc.m_var = 12 abc.m_var = 0 abc.m_var = 14 abc.m_var = 10 ncsim: *W,RNQUIE: Simulation is complete.
Every value of m_var this time falls outside the range [3:7] — exactly the opposite of the previous example, since the constraint now explicitly excludes that range instead of restricting to it.
Quick Check
Q: With this inverted constraint, could abc.m_var ever randomize to exactly 5?
Show Answer
No. 5 falls inside [3:7], and the constraint explicitly requires m_var to be outside that range — 5 is one of the values this constraint rules out entirely.
Practical Example
Say a memory is located between address 0x4000 and 0x5FFF, partitioned into two halves — one for instructions, one for data. To randomize an address that's guaranteed to fall within the data half of memory, inside is a natural fit:
class Data;
rand bit [15:0] m_addr;
constraint c_addr { m_addr inside {[16'h5000:16'h5fff]}; }
endclass
module tb;
initial begin
Data data = new();
repeat (5) begin
data.randomize();
$display ("addr = 0x%0h", data.m_addr);
end
end
endmodule
Output
ncsim> run addr = 0x58ef addr = 0x563f addr = 0x5612 addr = 0x5249 addr = 0x5cee ncsim: *W,RNQUIE: Simulation is complete.
Every generated address falls between 0x5000 and 0x5FFF — squarely within the data region, never straying into the instruction half of memory.
Where Is This Used?
inside is the standard way to express both "must be one of these specific values" (like a small set of legal opcodes) and "must fall within this range" (like a valid address window) without writing out a long chain of || comparisons. Its inverted form is equally common for explicitly carving out reserved or illegal ranges a randomized value must never land on.
Common Beginner Mistakes
Mistake #1: Assuming a range is exclusive of its endpoints
As the first example shows, [4:9] includes both 4 and 9 themselves. Why? It's easy to assume a range excludes its boundary values by default — inside ranges are always inclusive on both ends unless the values themselves are written to exclude them.
Mistake #2: Forgetting where the ! belongs in an inverted inside
The negation wraps the entire expression: !(m_var inside {[3:7]}), not m_var !inside {[3:7]}. Why? inside itself has no built-in negated form — the ! operator negates the whole boolean result of the inside check.
Mistake #3: Confusing a value list with a range
{4, 7, 9} matches only those three exact values; {[4:9]} matches every value from 4 through 9. Why? The square brackets specifically signal a contiguous range — mixing up the two syntaxes silently changes which values are actually considered legal.
Mistake #4: Assuming inside only works inside a constraint block
As the conditional-statement example shows, inside works identically in an if, a ternary operator, or any other boolean expression — not just inside a constraint block. Why? It's a general-purpose membership operator, and constraints are simply one common place it gets used.
Practice Exercise
Challenge: Constrain an Address Outside a Reserved Region
A device has address space 0x0000 to 0xFFFF, with 0x8000–0x80FF reserved for internal use. Write a constraint on a rand bit [15:0] addr that keeps randomized addresses out of the reserved region.
Hint
Use the inverted form of inside, the same way this article's own "Inverted inside" section excludes a range rather than restricting to one.
Solution
class DeviceAddr;
rand bit [15:0] addr;
constraint c_addr { !(addr inside {[16'h8000:16'h80FF]}); }
endclass
This allows any address in the full 16-bit space except the reserved 0x8000–0x80FF window — the same inverted-inside pattern used earlier in this article, just applied to a realistic reserved-address scenario.
Summary
In this tutorial, you learned:
insidechecks whether a value matches an explicit list of values or falls within an inclusive range- It works identically inside conditional statements (
if, ternary) and inside constraint blocks - Wrapping the entire expression in
!(...)inverts the check, excluding a range instead of restricting to it - A value-list (
{4, 7, 9}) and a range ({[4:9]}) use similar-looking syntax but mean very different things
Why Learn About 2-State Data Types? A logic variable can hold four values, but most testbench code never needs the extra two. A packet length, a loop counter, an array index — none of these should ever legitimately be X or Z. SystemVerilog's 2-state types like bit, byte, and int exist for exactly this kind of data: plain numbers, modeled the same way a C program would.
4-state types and the logic keyword were already covered in SystemVerilog logic and Verilog Data Types. This article covers the other half: SystemVerilog's family of 2-state integer types.
8 min read | Beginner Level
What You'll Learn
- Why 2-state types exist and how they differ from 4-state types
- The five 2-state integer types and how their ranges compare
- What happens when a 4-state value is assigned to a 2-state variable
- How to work with signed and unsigned values, and how to cast between them
2-State Data Types
2-state data types like bit and int can only represent 0 and 1 — there's no X or Z. That simplification means each bit needs only one bit of simulator storage instead of two, which reduces memory use and speeds up simulation.
| Data Type | Size | Signed Range | Unsigned Range | Description |
|---|---|---|---|---|
bit | 1-bit | — | 0 and 1 | 2-state variable |
byte | 8-bit | -2⁷ to 2⁷-1 | 0 to 2⁸-1 | 2-state variable, similar to C char |
shortint | 16-bit | -2¹⁵ to 2¹⁵-1 | 0 to 2¹⁶-1 | 2-state variable, similar to C short int |
int | 32-bit | -2³¹ to 2³¹-1 | 0 to 2³²-1 | 2-state variable, similar to C int |
longint | 64-bit | -2⁶³ to 2⁶³-1 | 0 to 2⁶⁴-1 | 2-state variable, similar to C long int |
2-state types suit more abstract levels of modeling than RTL, such as system-level or transaction-level code. When modeling a network packet with a header field for length, that length should be a plain number — there's no meaningful scenario where it should read as unknown or high-impedance.
When a 4-state value is converted to a 2-state value, any X or Z bits are converted to 0.
module tb;
bit [3:0] var_b; // Declare a 4-bit variable of type "bit"
logic [3:0] x_val; // Declare a 4-bit variable of type "logic"
initial begin
x_val = 4'b01zx;
// If a logic type or any 4-state variable assigns its value to a "bit" type
// variable, then X and Z get converted to zero
var_b = x_val;
$display ("x_val=%b var_b = %b", x_val, var_b);
end
endmodule
Output
xcelium> run x_val=01zx var_b = 0100 xmsim: *W,RNQUIE: Simulation is complete.
x_val holds a Z in bit 1 and an X in bit 0. Once that value is assigned into the 2-state var_b, both unknown bits collapse to 0, giving 0100. This silent collapsing is exactly why 2-state types are the wrong choice for RTL signals that genuinely need to represent an unknown or undriven state — see SystemVerilog logic for that side of the picture.
Quick Check
Q: What does a 2-state variable read back as, if a 4-state signal assigned into it was holding Z?
Show Answer
0. Any X or Z bit is silently converted to 0 the moment it's assigned into a 2-state type — there's no error or warning by default.
bit
The bit type is a 2-state type that defaults to 0. It's the most commonly used 2-state type in testbenches and other verification code, where the extra X/Z states aren't needed. A range specification ([MSB:LSB]) turns a single bit into a multi-bit vector.
Syntax
bit signal_name; // single-bit
bit [msb:lsb] signal_name; // multi-bit vector
module tb;
bit var_a; // Declare a 1 bit variable of type "bit"
bit [3:0] var_b; // Declare a 4 bit variable of type "bit"
logic [3:0] x_val; // Declare a 4 bit variable of type "logic"
initial begin
// Initial value of "bit" data type is 0
$display ("Initial value var_a=%0b var_b=0x%0h", var_a, var_b);
// Assign new values and display the variable to see that it gets the new values
var_a = 1;
var_b = 4'hF;
$display ("New values var_a=%0b var_b=0x%0h", var_a, var_b);
// If a "bit" type variable is assigned with a value greater than it can hold
// the left most bits are truncated. In this case, var_b can hold only 4 bits
// and hence 'h481 gets truncated leaving var_b with only 'ha;
var_b = 16'h481a;
$display ("Truncated value: var_b=0x%0h", var_b);
end
endmodule
Output
ncsim> run Initial value var_a=0 var_b=0x0 New values var_a=1 var_b=0xf Truncated value: var_b=0xa ncsim: *W,RNQUIE: Simulation is complete.
var_b is only 4 bits wide, so assigning it 16'h481a keeps only the bottom 4 bits (a) and silently discards the rest — no error, no truncation warning by default.
This kind of silent truncation is one of the most common sources of "why is my value wrong" bugs. If a variable might receive a value wider than its declared width, check the width explicitly rather than relying on the assignment to catch it.
byte
The byte type is an 8-bit, 2-state integer, signed by default, using two's complement representation to hold both positive and negative values — a range of -128 to 127. It's a natural fit anywhere memory efficiency matters, such as large arrays of small values.
module tb;
byte m_var_s; // By default signed, and can represent positive and negative numbers
initial begin
#10 m_var_s = 0; // assign 0
#20 m_var_s = 2**7 - 1; // assign 127
#30 m_var_s = 2**7; // assign 128
#40 m_var_s = 2**8 - 1; // assign 255
end
initial
$monitor("[%0t] m_var_s = 'd%0d (0x%0h)", $time, m_var_s, m_var_s);
endmodule
Output
xcelium> run [0] m_var_s = 'd0 (0x0) [30] m_var_s = 'd127 (0x7f) [60] m_var_s = 'd-128 (0x80) [100] m_var_s = 'd-1 (0xff) xmsim: *W,RNQUIE: Simulation is complete.
Assigning 128 (one past the signed maximum of 127) wraps around to -128, and 255 wraps to -1 — classic two's-complement rollover, the same behavior you'd see assigning out-of-range values to a signed char in C.
Quick Check
Q: Why does assigning 255 to a signed byte display as -1, not 255?
Show Answer
255 in binary is 8'hFF, all eight bits set to 1. In two's-complement signed representation, that bit pattern represents -1, not 255 — the value itself never changes, only how it's interpreted based on whether the type is signed or unsigned.
shortint
shortint is a 2-state, 16-bit signed integer, exactly like byte but wider.
module tb;
shortint m_var_s; // By default signed, and can represent positive and negative numbers
initial begin
#10 m_var_s = 0; // assign 0
#20 m_var_s = 2**15 - 1; // assign 32767
#30 m_var_s = 2**15; // assign 32768 (wraps to -32768, signed 16-bit)
#40 m_var_s = 2**16 - 1; // assign 65535 (wraps to -1, signed 16-bit)
end
initial
$monitor("[%0t] m_var_s = 'd%0d (0x%0h)", $time, m_var_s, m_var_s);
endmodule
Output
xcelium> run [0] m_var_s = 'd0 (0x0) [30] m_var_s = 'd32767 (0x7fff) [60] m_var_s = 'd-32768 (0x8000) [100] m_var_s = 'd-1 (0xffff) xmsim: *W,RNQUIE: Simulation is complete.
Just like byte, values that overflow the signed 16-bit range wrap around: 32768 becomes -32768, and 65535 becomes -1 — exactly what the output above shows.
int
int is a 2-state, 32-bit signed integer — the default choice for general-purpose counters, loop variables, and array indices in a testbench.
module tb;
int m_var_s; // By default signed, and can represent positive and negative numbers
initial begin
#10 m_var_s = 0;
#20 m_var_s = 2**31 - 1;
#30 m_var_s = 2**31;
#40 m_var_s = 2**32 - 1;
end
initial
$monitor("[%0t] m_var_s = 'd%0d (0x%0h)", $time, m_var_s, m_var_s);
endmodule
Output
xcelium> run [0] m_var_s = 'd0 (0x0) [30] m_var_s = 'd2147483647 (0x7fffffff) [60] m_var_s = 'd-2147483648 (0x80000000) [100] m_var_s = 'd-1 (0xffffffff) xmsim: *W,RNQUIE: Simulation is complete.
int is by far the most commonly used integer type in testbench code — loop counters, transaction counts, and array sizes almost always default to int unless there's a specific reason to pick a narrower or wider type.
longint
longint is a 2-state, 64-bit signed integer, useful for counters or addresses that could exceed the 32-bit range of a plain int.
module tb;
longint m_var_s; // By default signed, and can represent positive and negative numbers
initial begin
#10 m_var_s = 0;
#20 m_var_s = 2**63 - 1;
#30 m_var_s = 2**63;
#40 m_var_s = 2**64 - 1;
end
initial
$monitor("[%0t] m_var_s = 'd%0d (0x%0h)", $time, m_var_s, m_var_s);
endmodule
Output
xcelium> run [0] m_var_s = 'd0 (0x0) [30] m_var_s = 'd9223372036854775807 (0x7fffffffffffffff) [60] m_var_s = 'd-9223372036854775808 (0x8000000000000000) [100] m_var_s = 'd-1 (0xffffffffffffffff) xmsim: *W,RNQUIE: Simulation is complete.
Signed and Unsigned
Signed types can represent both positive and negative values; unsigned types can only represent zero and positive values. A signed type spends one bit (the MSB) on the sign, which halves its maximum positive value compared to an unsigned type of the same width — the total range stays the same size, just shifted.
Example
The sign can be set explicitly with the signed and unsigned keywords.
module tb;
byte s_byte; // By default byte is signed
byte unsigned u_byte; // Byte is set to unsigned
initial begin
$display ("Size s_byte=%0d, u_byte=%0d", $bits(s_byte), $bits(u_byte));
// Assign the "assumed" maximum value to both variables
#1 s_byte = 'h7F;
u_byte = 'h7F;
// Increment by 1, and see that s_byte rolled over to negative because
// byte is signed by default. u_byte keeps increasing because it is
// unsigned and can go upto 255
#1 s_byte += 1;
u_byte += 1;
// Assign 255 (8'hFF) to u_byte -> this is the max value it can hold
#1 u_byte = 'hFF;
// Add 1 and see that it rolls over to 0
#1 u_byte += 1;
end
initial begin
$monitor ("[%0t ns] s_byte=%0d u_byte=%0d", $time, s_byte, u_byte);
end
endmodule
Output
ncsim> run Size s_byte=8, u_byte=8 [0 ns] s_byte=0 u_byte=0 [1 ns] s_byte=127 u_byte=127 [2 ns] s_byte=-128 u_byte=128 [3 ns] s_byte=-128 u_byte=255 [4 ns] s_byte=-128 u_byte=0 ncsim: *W,RNQUIE: Simulation is complete.
Both variables are 8 bits wide, but they interpret the same bit patterns differently: past 127, s_byte wraps to negative, while u_byte keeps counting up to 255 before it wraps to 0.
Quick Check
Q: Do signed and unsigned versions of the same type use a different number of bits?
Show Answer
No. As the example shows, $bits() returns 8 for both s_byte and u_byte — the width is identical. Only the interpretation of the top bit (as a sign, or as part of the magnitude) differs.
Sign Cast
Signed and unsigned values can be converted into one another with a cast, without changing the underlying bits.
module tb;
shortint m_var_s; // By default signed, and can represent positive and negative numbers
shortint unsigned m_var_us; // Explicitly set to 'unsigned' and represents only positive numbers
initial begin
m_var_us = 2**16 - 1;
m_var_s = -1;
// Convert an unsigned variable value to a signed variable value by casting
$display("m_var_us=%0d m_var_us=%0d", signed' (m_var_us), m_var_us);
$display("m_var_s=%0d m_var_s=%0d", unsigned' (m_var_s), m_var_s);
end
endmodule
Output
xcelium> run m_var_us=-1 m_var_us=65535 m_var_s=65535 m_var_s=-1 xmsim: *W,RNQUIE: Simulation is complete.
m_var_us and m_var_s hold the exact same 16-bit pattern (all 1s), just declared with opposite signedness — that's why signed'(m_var_us) reads as -1 and unsigned'(m_var_s) reads as 65535. The cast doesn't touch a single bit; it only changes how those bits are interpreted for that one expression. Note the first $display's format string prints the label m_var_us twice, once for the cast result and once for the plain value — a labeling quirk to watch for, not a difference in what's being computed.
Operations on unsigned integers can be marginally faster in some tools, since there's no sign bit to account for during arithmetic — one more reason to reach for unsigned explicitly when a value can never legitimately go negative, like an index or a count.
Common Mistakes
Mistake #1: Assuming truncation or overflow raises a warning
As var_b = 16'h481a; showed, assigning a value that's too wide for the target variable silently keeps only the low bits — there's no default warning. The same applies to signed overflow, like byte wrapping from 127 to -128. Don't rely on the simulator to flag either case; check widths and ranges explicitly where it matters.
Mistake #2: Using a 2-state type where X/Z detection matters
A 2-state variable can never hold X or Z — any 4-state value assigned into one gets those bits silently zeroed. This makes 2-state types a poor choice for signals where catching an uninitialized or undriven condition is the whole point, such as most RTL signals. Use logic for those instead.
Mistake #3: Forgetting that signed and unsigned share the same width
byte and byte unsigned are both 8 bits — adding unsigned doesn't gain you an extra bit of storage, it only shifts which values that same 8 bits can represent (0 to 255 instead of -128 to 127).
Mistake #4: Assuming a cast changes the stored value
signed'(...) and unsigned'(...) only change how an expression's existing bits are interpreted for that one use — they don't modify the variable itself. Casting m_var_us doesn't turn m_var_us into a signed variable; it produces a signed view of its value for that expression only.
Practice Exercise
Challenge: Explore Unsigned Rollover
Declare a shortint unsigned variable named counter. Assign it its maximum possible value, then add 1 to it and print the result. Also print $bits(counter) to confirm the width.
Hint
The maximum value of a 16-bit unsigned type is 2**16 - 1. Adding 1 past that should roll over to 0, the same way u_byte did in the Signed and Unsigned example.
Solution
module tb;
shortint unsigned counter;
initial begin
$display ("bits = %0d", $bits(counter));
counter = 2**16 - 1;
$display ("counter = %0d", counter);
counter += 1;
$display ("counter = %0d (rolled over)", counter);
end
endmodule
Summary
In this tutorial, you learned:
- 2-state types can only hold
0and1, use less simulator memory than 4-state types, and are best suited to abstract, non-RTL data like counters and packet fields bit,byte,shortint,int, andlongintrange from 1 to 64 bits, each signed by default exceptbit- Assigning a 4-state value into a 2-state variable silently converts any
X/Zbits to0 - Assigning a value wider than a variable's declared width silently truncates it, and signed overflow wraps around — neither raises a warning by default
signed'(...)andunsigned'(...)reinterpret an expression's existing bits without changing the underlying variable
SystemVerilog is an extension to Verilog and is also used as an HDL. Verilog has reg and wire data types to describe hardware behavior, but verifying hardware is more complex and demanding than describing it. Plain Verilog data types aren't sufficient to build efficient testbenches and testcases, so SystemVerilog extends Verilog with more C-like data types for better encapsulation and compactness.
Click here to refresh Verilog Data Types
The image below is a comprehensive list of the major basic data types available in SystemVerilog.
10 min read | Beginner Level
What You'll Learn
- The four-state value system every SystemVerilog signal is built on
- How SystemVerilog's enhanced fill literals and unbased literals simplify sizing
- Working with strings, structures, and fixed arrays for testbench data
- How
void, and real-to-int conversion, behave in SystemVerilog
Comments
// This is a one-line comment
/* This is a multiple line comment.
Since this line is within the block comment symbols, it is a comment.
*/
/* Another multiple line comment
// A nested one-line comment inside a block comment is fine.
But a block comment cannot be nested in another block comment.
*/
Value System
Following are the four states that a variable or net can hold:
| State | Description |
|---|---|
| 0 | Logic state 0 - variable/net is at 0 volts |
| 1 | Logic state 1 - variable/net is at some value greater than 0.7 volts |
| x or X | Logic state X - variable/net could be either 0 or 1 - we just don't know |
| z or Z | Logic state Z - net has high impedance - maybe the wire is not connected and is floating |
Enhanced (') Literal
Verilog allowed a vector to be easily left-padded with 0, Z, or X, but not with 1. This becomes a real limitation once the WIDTH parameter grows, as shown below:
parameter WIDTH = 8;
reg [WIDTH-1:0] m_var;
m_var = 'h0; // Fills all bits of m_var with 0
m_var = 'hZ; // Fills all bits of m_var with Z
m_var = 'hX; // Fills all bits of m_var with X
m_var = 'h1; // Only LSB is 1 making the value of m_var = 8'b0000_0001
m_var = {WIDTH{1'b1}}; // Workaround - Use concatenation operator to club together as many 1s required
SystemVerilog allows the fill value to be specified without needing to indicate a binary, octal, or hexadecimal radix. Additionally, the fill value can now also be set to a logic 1:
module tb;
reg [7:0] m_var1;
reg [15:0] m_var2;
initial begin
m_var1 = '1;
m_var2 = '1;
$display("m_var1=0x%0h m_var2=0x%0h", m_var1, m_var2);
// This does not work - Radix must be specified !
//m_var1 = 'F0;
//m_var2 = 'cafe;
end
endmodule
xcelium> run m_var1=0xff m_var2=0xffff xmsim: *W,RNQUIE: Simulation is complete.
The '0, '1, 'x, and 'z forms only work as single-digit unbased literals. Multi-digit fill values like 'F0 or 'cafe still need an explicit radix, which is why they're commented out above.
Floating Point/Exponential Numbers
SystemVerilog's real type sets a fixed-point format (e.g. 2.8) or exponent format (e.g. 7.2e6):
module tb;
real pi; // Declared to be of type real
real freq;
initial begin
pi = 3.14; // Store floating point number
freq = 1e6; // Store exponential number
$display ("Value of pi = %f", pi);
$display ("Value of pi = %0.3f", pi);
$display ("Value of freq = %0d", freq);
end
endmodule
xcelium> run Value of pi = 3.140000 Value of pi = 3.140 Value of freq = 1000000 xmsim: *W,RNQUIE: Simulation is complete.
Strings
// Strings can be split into multiple lines [for visual appeal] by the using "" character
// A raw newline inside a string literal is illegal unless the line ends with "\" (line continuation)
// The "\" continuation is dropped, so this does NOT add a newline to the output
// Result: New York is an awesome place. So energetic and vibrant.
$display ("New York is an awesome place. \
So energetic and vibrant.");
// Use the "\n" escape sequence to actually generate a newline in the output
// Result:
// New York is an awesome place.
// So energetic and vibrant.
$display ("New York is an awesome place.\nSo energetic and vibrant.");
// To store a string literal in an integral type, each character will require 8 bits
byte myLetter = "D";
bit [7:0] myNewLine = "\n";
// "Hello World" has 11 characters and each character requires 8-bits
bit [8*11:1] myMessage = "Hello World";
string myMessage2 = "Hello World"; // Uses "string" data type
Click here to learn more about SystemVerilog Strings
Structures
A structure represents a collection of data types that are stored together and can be referenced via the structure variable.
// Create a structure to store "int" and "real" variables
// A name is given to the structure and declared to be a data type so
// that this name "s_money" can be used to create structure variables
typedef struct {
int coins;
real dollars;
} s_money;
// Create a structure variable of type s_money
s_money wallet;
wallet = '{5, 19.75}; // Assign direct values to a structure variable
wallet = '{coins:5, dollars:19.75}; // Assign values using member names
wallet = '{default:0}; // Assign all elements of structure to 0
wallet = s_money'{int:1, dollars:2}; // Type-key (int:1) sets coins to 1; name-key sets dollars to 2 directly
// Create a structure that can hold 3 variables and initialize them with 1
struct {
int A, B, C;
} ABC = '{3{1}}; // A = B = C = 1
// Assigning an array of structures
s_money purse [1:0] = '{'{2, 4.25}, '{7,1.5}};
Common Mistake: Structure literals use the '{...} syntax, not a plain {...}. Dropping the leading apostrophe is one of the most common beginner errors with structures.
Quick Check
Q: What does wallet = '{default:0}; do?
Show Answer
It sets every member of the wallet structure - both coins and dollars - to 0, without needing to name each member individually.
Click here to learn more about Structures
Fixed Arrays
An array is a variable that stores multiple values of the same type, each reached by its index.
module tb;
// The following two representations of fixed arrays are the same
// myFIFO and urFIFO have 8 locations where each location can hold an integer value
// [0] | [1] | [2] | [3] | [4] | [5] | [6] | [7]
int myFIFO [0:7];
int urFIFO [8];
// Multi-dimensional arrays
// [0][0] | [0][1] | [0][2]
// [1][0] | [1][1] | [1][2]
int myArray [2][3];
initial begin
myFIFO[5] = 32'hface_cafe; // Assign value to location 5 in 1D array
myArray [1][1] = 7; // Assign to location 1,1 in 2D array
// Iterate through each element in the array
foreach (myFIFO[i])
$display ("myFIFO[%0d] = 0x%0h", i, myFIFO[i]);
// Iterate through each element in the multidimensional array
foreach (myArray[i])
foreach (myArray[i][j])
$display ("myArray[%0d][%0d] = %0d", i, j, myArray[i][j]);
end
endmodule
ncsim> run myFIFO[0] = 0x0 myFIFO[1] = 0x0 myFIFO[2] = 0x0 myFIFO[3] = 0x0 myFIFO[4] = 0x0 myFIFO[5] = 0xfacecafe myFIFO[6] = 0x0 myFIFO[7] = 0x0 myArray[0][0] = 0 myArray[0][1] = 0 myArray[0][2] = 0 myArray[1][0] = 0 myArray[1][1] = 7 myArray[1][2] = 0 ncsim: *W,RNQUIE: Simulation is complete.
Click here to learn more about SystemVerilog Arrays
Void
The void data type represents non-existing data, and is specified as the return type of a function to indicate that it returns no value:
function void display ();
$display ("Am not going to return any value");
endfunction
task void display ();
#10 $display ("Me neither");
endtask
Factual note: The task void display () line above doesn't reflect valid SystemVerilog syntax. Tasks never declare a return type at all - that's precisely what distinguishes a task from a function in the language, since only functions can return a value (or explicitly return none via void). If you need to model "no return value" behavior, use a plain task without any return type.
real to int Conversion
Real numbers are converted to integers by rounding to the nearest integer, not by truncating. If the fractional part is exactly 0.5, it's rounded away from zero. Explicit conversion can be done via casting or via system tasks - and directly assigning a real value to an integral type also rounds rather than truncates.
// Casting will perform rounding
int'(2.0 * 3.0)
shortint'({8'hab, 8'hef})
// Using system tasks will truncate
integer $rtoi ( real_val )
real $itor ( int_val)
Where Are These Data Types Used?
In real verification environments, string is used constantly for test names, config file paths, and log messages; struct is used to bundle related transaction fields (like address, data, and control bits) into one object; and real shows up in analog-mixed-signal and power-aware testbenches where exact timing or voltage values matter.
Common Beginner Mistakes
Mistake #1: Using 'F0 or 'cafe as a fill literal.
Unbased unsized literals only support the single digits 0, 1, x, or z. Anything with a radix or multiple digits, like 'hF0, needs the radix spelled out explicitly.
Mistake #2: Writing {...} instead of '{...} for structure assignments.
Plain curly braces are a concatenation, not a structure literal. Forgetting the leading apostrophe on a structure assignment is one of the most common syntax errors beginners run into.
Mistake #3: Assuming void applies to tasks the same way it applies to functions.
Only functions declare a return type. Tasks never do, since they're not allowed to return a value at all - see the factual note under Void above.
Practice Exercise
Challenge: Fix the Fill Value
Given reg [15:0] status;, write a single-line SystemVerilog assignment that sets every bit of status to 1, using the enhanced literal syntax introduced in this article rather than the old concatenation workaround.
Hint
You don't need to specify a radix or a width for this one - SystemVerilog's unbased unsized literal handles it.
Solution
status = '1;
This fills all 16 bits of status with 1, regardless of how wide the variable is - no need to know or repeat its width, unlike the {WIDTH{1'b1}} workaround shown earlier.
Summary
In this tutorial, you learned:
- The four-state value system (0, 1, X, Z) that underlies every SystemVerilog signal
- Enhanced (') literals let you fill a vector with 0, 1, X, or Z without knowing its width
- real stores floating-point and exponential numbers, while string stores text without a fixed bit width
- Structures bundle related variables together, but require
'{...}syntax for literal assignments - Fixed arrays store multiple values in contiguous locations and can be 1D or multi-dimensional
- void marks a function that returns nothing; real-to-int conversions round rather than truncate
SystemVerilog arrays come with a rich set of built-in methods for searching, ordering, and reducing their contents — without you having to hand-write a single loop.
Each method iterates through the array elements and evaluates the expression given in the with clause for every element. The iterator argument names the local variable used to refer to the current element inside that expression; if you don't provide one, item is used by default.
Specifying an iterator argument without a with clause is illegal — the iterator only exists to be used inside the expression.
10 min read | Intermediate Level
What You'll Learn
- How the
withclause and iterator argument work across array methods - Search and filter arrays using locator methods like
find()andfind_index() - Reorder arrays in place with
sort(),rsort(),reverse(), andshuffle() - Collapse an array down to a single value using reduction methods like
sum()andxor()
Syntax
Every array manipulation method follows the same general call pattern.
array_name.method_name(iterator_name) with (expression); // custom iterator
array_name.method_name with (expression); // default iterator: item
array_name.method_name(); // no expression needed
method_name– one of the locator, ordering, or reduction methods covered belowiterator_name– optional local variable name representing the current element; defaults toitemwith (expression)– a boolean or value expression evaluated per element; mandatory for some methods, optional for others, and disallowed for a few
Array Locator Methods
Locator methods search through an array and return either the matching elements or their indices, without modifying the original array.
Mandatory 'with' Clause
These methods filter elements based on a given expression and collect every element that satisfies it, so the with clause is required.
| Method | Description |
|---|---|
find() | Returns all elements satisfying the given expression |
find_index() | Returns the indices of all elements satisfying the given expression |
find_first() | Returns the first element satisfying the given expression |
find_first_index() | Returns the index of the first element satisfying the given expression |
find_last() | Returns the last element satisfying the given expression |
find_last_index() | Returns the index of the last element satisfying the given expression |
Example
module tb;
int array[9] = '{4, 7, 2, 5, 7, 1, 6, 3, 1};
int res[$];
initial begin
res = array.find(x) with (x > 3);
$display ("find(x) : %p", res);
res = array.find_index with (item == 4);
$display ("find_index : res[%0d] = 4", res[0]);
res = array.find_first with (item < 5 & item >= 3);
$display ("find_first : %p", res);
res = array.find_first_index(x) with (x > 5);
$display ("find_first_index: %p", res);
res = array.find_last with (item <= 7 & item > 3);
$display ("find_last : %p", res);
res = array.find_last_index(x) with (x < 3);
$display ("find_last_index : %p", res);
end
endmodule
Output
ncsim> run
find(x) : '{4, 7, 5, 7, 6}
find_index : res[0] = 4
find_first : '{4}
find_first_index: '{1}
find_last : '{6}
find_last_index : '{8}
ncsim: *W,RNQUIE: Simulation is complete.
Notice that find_index and find both use the default iterator item in some calls and a custom iterator x in others — either works as long as the name matches what's used inside the with expression. The find_index line's $display is a bit of a pun: res[0] holds the index (0) where the value 4 was found, so the format string reads as "the index found is 0, and the value there is 4."
Quick Check
Q: Is calling array.find_index() without a with clause legal?
Show Answer
No. For all six methods in this table — find, find_index, find_first, find_first_index, find_last, and find_last_index — the with clause is mandatory. Omitting it is a compile-time error.
Optional 'with' Clause
These methods work with or without a with clause — used alone they operate on the raw element values, and with a clause they operate on the expression result instead.
| Method | Description |
|---|---|
min() | Returns the element with minimum value, or whose expression evaluates to a minimum |
max() | Returns the element with maximum value, or whose expression evaluates to a maximum |
unique() | Returns all elements with unique values, or whose expression evaluates to a unique value |
unique_index() | Returns the indices of all elements with unique values, or whose expression evaluates to a unique value |
Example
module tb;
int array[9] = '{4, 7, 2, 5, 7, 1, 6, 3, 1};
int res[$];
initial begin
res = array.min();
$display ("min : %p", res);
res = array.max();
$display ("max : %p", res);
res = array.unique();
$display ("unique : %p", res);
res = array.unique(x) with (x < 3);
$display ("unique : %p", res);
res = array.unique_index;
$display ("unique_index : %p", res);
end
endmodule
Output
ncsim> run
min : '{1}
max : '{7}
unique : '{4, 7, 2, 5, 1, 6, 3}
unique : '{4, 2}
unique_index : '{0, 1, 2, 3, 5, 6, 7}
ncsim: *W,RNQUIE: Simulation is complete.
The second unique call is the interesting one: array.unique(x) with (x < 3) doesn't return elements with unique values — it groups elements by the boolean result of x < 3, and returns one element for each distinct result (one for false, one for true). This simulator kept the first element of each group, but the standard does not say which element is kept or in what order they are returned. That's why it collapses down to just '{4, 2}' instead of the full array.
Locator methods are a natural fit for scoreboard and reference-model code — for example, using find_first with (item.addr == expected_addr) to pull a matching transaction out of a list of received packets.
Array Ordering Methods
Unlike locator methods, ordering methods operate on and alter the array directly — there's no separate result to capture.
| Method | Description |
|---|---|
reverse() | Reverses the order of elements in the array; a with clause is not allowed here either |
sort() | Sorts the array in ascending order, optionally using a with clause |
rsort() | Sorts the array in descending order, optionally using a with clause |
shuffle() | Randomizes the order of the elements in the array; a with clause is not allowed here |
Example
module tb;
int array[9] = '{4, 7, 2, 5, 7, 1, 6, 3, 1};
initial begin
array.reverse();
$display ("reverse : %p", array);
array.sort();
$display ("sort : %p", array);
array.rsort();
$display ("rsort : %p", array);
for (int i = 0; i < 5; i++) begin
array.shuffle();
$display ("shuffle Iter:%0d = %p", i, array);
end
end
endmodule
Output
ncsim> run
reverse : '{1, 3, 6, 1, 7, 5, 2, 7, 4}
sort : '{1, 1, 2, 3, 4, 5, 6, 7, 7}
rsort : '{7, 7, 6, 5, 4, 3, 2, 1, 1}
shuffle Iter:0 = '{6, 7, 1, 7, 3, 2, 1, 4, 5}
shuffle Iter:1 = '{5, 1, 3, 4, 2, 7, 1, 7, 6}
shuffle Iter:2 = '{3, 1, 7, 4, 6, 7, 1, 2, 5}
shuffle Iter:3 = '{6, 4, 7, 3, 1, 7, 5, 2, 1}
shuffle Iter:4 = '{3, 6, 2, 5, 4, 7, 7, 1, 1}
ncsim: *W,RNQUIE: Simulation is complete.
Each call mutates array in place and builds on the result of the previous call — sort() runs on whatever order reverse() left behind, and rsort() runs on whatever sort() left behind. The final multiset of values never changes; only the order does.
Quick Check
Q: Which of reverse(), sort(), rsort(), and shuffle() do not accept a with clause?
Show Answer
reverse() and shuffle(). Neither orders by a value — reverse() just flips the existing order and shuffle() randomizes it — so a with expression wouldn't have anything meaningful to act on for either one; specifying one for either method is a compiler error. sort() and rsort() both accept an optional with clause.
Using Array Ordering on Classes
The with clause makes sort() and rsort() useful on arrays of class objects too, letting you sort by one or more object properties instead of the raw element value.
class Register;
string name;
rand bit [3:0] rank;
rand bit [3:0] pages;
function new (string name);
this.name = name;
endfunction
function void print();
$display("name=%s rank=%0d pages=%0d", name, rank, pages);
endfunction
endclass
module tb;
Register rt[4];
string name_arr[4] = '{"alexa", "siri", "google home", "cortana"};
initial begin
$display ("
-------- Initial Values --------");
foreach (rt[i]) begin
rt[i] = new (name_arr[i]);
rt[i].randomize();
rt[i].print();
end
$display ("
--------- Sort by name ------------");
rt.sort(x) with (x.name);
foreach (rt[i]) rt[i].print();
$display ("
--------- Sort by rank, pages -----------");
rt.sort(x) with ( {x.rank, x.pages});
foreach (rt[i]) rt[i].print();
end
endmodule
Output
ncsim> run -------- Initial Values -------- name=alexa rank=12 pages=13 name=siri rank=6 pages=12 name=google home rank=12 pages=13 name=cortana rank=7 pages=11 --------- Sort by name ------------ name=alexa rank=12 pages=13 name=cortana rank=7 pages=11 name=google home rank=12 pages=13 name=siri rank=6 pages=12 --------- Sort by rank, pages ----------- name=siri rank=6 pages=12 name=cortana rank=7 pages=11 name=alexa rank=12 pages=13 name=google home rank=12 pages=13 ncsim: *W,RNQUIE: Simulation is complete.
Concatenating {x.rank, x.pages} inside the second with clause sorts by rank first and uses pages as a tiebreaker — notice alexa and google home share rank=12 and pages=13, so their relative order stays exactly as it was going in, since the sort has nothing left to distinguish them by.
Sorting class-object arrays by a struct-like key such as {x.rank, x.pages} is a common pattern for ordering a queue of transactions by priority and then by arrival time, without writing a custom compare function.
Array Reduction Methods
Reduction methods collapse every element in the array down into a single value.
| Method | Description |
|---|---|
sum() | Returns the sum of all array elements |
product() | Returns the product of all array elements |
and() | Returns the bitwise AND (&) of all array elements |
or() | Returns the bitwise OR (|) of all array elements |
xor() | Returns the bitwise XOR (^) of all array elements |
module tb;
int array[4] = '{1, 2, 3, 4};
int res[$];
initial begin
$display ("sum = %0d", array.sum());
$display ("product = %0d", array.product());
$display ("and = 0x%0h", array.and());
$display ("or = 0x%0h", array.or());
$display ("xor = 0x%0h", array.xor());
end
endmodule
Output
ncsim> run sum = 10 product = 24 and = 0x0 or = 0x7 xor = 0x4 ncsim: *W,RNQUIE: Simulation is complete.
Reduction methods map directly onto hardware-style checks in a testbench — xor() over a data array is a quick way to model a parity check, and sum() is handy for a running total when self-checking a counter or accumulator against your DUT.
Common Mistakes
Mistake #1: Omitting the mandatory 'with' clause
Calling array.find() or array.find_first_index() without a with clause is a compile error, since these methods have nothing to filter by otherwise. Only the min/max/unique family and the reduction methods can be called with no clause at all.
Mistake #2: Adding a 'with' clause to shuffle()
array.shuffle() with (item) is illegal — shuffle() randomizes order and doesn't accept a with clause under any circumstance, unlike sort() and rsort().
Mistake #3: Confusing find() with find_index()
find() returns the matching values; find_index() returns the matching positions in the array. Mixing these up is a common source of off-by-one bugs when the result is used to index back into the original array.
Mistake #4: Assuming ordering methods return a new array
array.sort() and array.reverse() mutate array directly and don't return a usable value — writing sorted = array.sort(); doesn't do what it looks like it does. If you need to keep the original order too, copy the array first.
Practice Exercise
Challenge: Filter, Sort, and Reduce
Given int vals[6] = '{12, 5, 9, 5, 20, 9};, use array methods to: find all elements greater than 8, sort a copy of the array in descending order, and compute the sum of the original array.
Hint
Use find() with a with clause for the filter step, copy the array into a new variable before calling rsort() so the original is untouched, and call sum() directly on the original.
Solution
module tb;
int vals[6] = '{12, 5, 9, 5, 20, 9};
int above8[$];
int sorted_copy[6];
initial begin
above8 = vals.find(x) with (x > 8);
$display("above8 = %p", above8);
sorted_copy = vals;
sorted_copy.rsort();
$display("sorted_copy (desc) = %p", sorted_copy);
$display("sum of vals = %0d", vals.sum());
end
endmodule
Summary
In this tutorial, you learned:
- Array manipulation methods use a shared
withclause and iterator pattern, withitemas the default iterator name - Locator methods like
find()andfind_index()search and filter without altering the array; thewithclause is mandatory for most of them - Ordering methods like
sort(),rsort(), andreverse()mutate the array in place;shuffle()never accepts awithclause sort()/rsort()can order arrays of class objects by one or more properties using thewithclause- Reduction methods like
sum()andxor()collapse the whole array into a single value, useful for checksums and running totals
Modern chips can contain billions of transistors, and that scale creates two very different problems. On the design side, describing that much hardware correctly and efficiently gets harder with plain Verilog. On the verification side, proving that a design this complex actually behaves as intended — before it's fabricated — becomes a massive task on its own. SystemVerilog grew out of Verilog to address both sides of that complexity at once.
This article introduces what SystemVerilog is, why it exists alongside Verilog, and how its design and verification capabilities fit into the overall chip development flow. It sets the foundation for everything else in this tutorial series.
Writing RTL? SystemVerilog for RTL Design is a short reading guide to the articles in this tutorial that matter for design.
8 min read | Beginner Level
What You'll Learn
- What SystemVerilog is and how it relates to Verilog
- How SystemVerilog's features split between RTL design and verification
- Why complex chips need dedicated design and verification languages
- What to focus on in each half: the hardware a design construct builds, and what a verification construct lets a testbench do
Getting the Most Out of This Tutorial
Most people first open a SystemVerilog page to find out how a construct is written. That part is quick to learn and easy to look up again, and editors and AI assistants can now write correct SystemVerilog for you. What is still yours to judge is whether the code does what you meant. The most useful way to work through this tutorial is to ask one question about every construct, and the question depends on which half of the language it belongs to.
For a design construct, ask what hardware it builds. A packed struct 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. An enum used for FSM states becomes a state register, and its names exist for people reading the code and the waveforms. An interface is a bundle of wires between modules. If you can say what hardware a construct produces, you can read any RTL that uses it.
For a verification construct, ask what it lets your testbench do. Classes let you build components once and reuse them. Randomization with constraints creates thousands of legal stimulus patterns that nobody wrote by hand. Functional coverage measures which of those patterns actually happened. Assertions check a rule on every clock cycle without a line of checking code in the test.
Both questions start from knowing what you want: the registers and interfaces of the design, or the stimulus, checks and coverage the testbench needs. Asking these questions of every example you read is what lets you tell whether a piece of SystemVerilog, your own or a tool's, does what you meant.
What Is SystemVerilog?
Hardware Description Languages (HDLs) like Verilog and VHDL describe hardware behavior so that it can eventually be synthesized into combinational gates and sequential elements (flip-flops, latches, muxes). But describing hardware is only half the job — you also need to prove that the description is correct before it becomes a physical chip.
SystemVerilog is an extension of Verilog, and it grew in two directions at once. On the design side, it adds cleaner, less error-prone constructs — always_comb, always_ff, enum, struct, and interface among others — that are fully synthesizable and increasingly used to write RTL instead of plain Verilog. On the verification side, it adds object-oriented programming (OOP) features, constrained-random stimulus generation, functional coverage, and assertions, turning it into a full Hardware Verification Language (HVL) capable of building complex, reusable testbenches.
SystemVerilog is a superset of Verilog. Every legal Verilog file is also legal SystemVerilog, but not every SystemVerilog construct (like class) is synthesizable — those are reserved for testbench code.
Where Is SystemVerilog Used?
On the design side, engineers use SystemVerilog's synthesizable constructs to write RTL for processors, GPUs, memory controllers, and SoC sub-blocks. On the verification side, it's the dominant language behind UVM (Universal Verification Methodology), which most large verification teams standardize on for building reusable test environments.
Why Wasn't Verilog Enough?
Back in the 1990s, Verilog was sufficient to design and verify chips that were small and relatively simple. As designs grew into millions of gates with many interacting sub-blocks, gaps showed up on both sides.
On the design side, Verilog's always block is easy to misuse — the same syntax can accidentally infer a latch instead of a flip-flop, and there's no built-in way to express an enumerated state or a bundled group of signals. On the verification side, Verilog lacks classes, constrained randomization, and built-in coverage collection, making it hard to build stimulus generators and checkers that scale to large designs. SystemVerilog was created to close both gaps: safer, more expressive constructs for RTL design, plus a full OOP toolkit for scalable, reusable verification environments.
SystemVerilog for Design vs. Verification
Not every SystemVerilog feature belongs on both sides of the flow. Some constructs are synthesizable and meant for describing hardware; others exist purely to make testbenches more powerful and are never intended to become real gates.
| Used for RTL Design (synthesizable) | Used for Verification only |
|---|---|
always_comb, always_ff, always_latch | class, constraint, randomize |
logic data type | mailbox, semaphore, event |
enum, struct, typedef | covergroup, coverpoint |
interface, modport | Virtual interfaces, virtual methods |
A quick rule of thumb: if a construct can hold state without a clock, allocate memory dynamically, or spawn a random value, it almost certainly belongs to the verification-only column.
Why Do Chips Need Verification?
Verification is the process of confirming that a hardware design behaves the way it's supposed to, before it goes to fabrication. Chip manufacturing is extremely expensive and slow, so catching a functional bug early — during simulation — is far cheaper than catching it after the chip comes back from the fab.
If a bug is discovered late in the design flow, the affected steps often have to be repeated. If it's serious enough to require re-fabricating the chip, that's called a respin, and it can set a project back by months and a significant amount of money. This is exactly why design and verification are treated as separate, equally important disciplines on any real chip project — a brilliantly designed block is only as good as the testbench that proves it works. Blocks that pass on their own are then checked again as one chip, which SoC verification covers.
Common Misconception: A testbench is not part of the final chip. It exists only in simulation to drive and check the design — none of its code gets synthesized into hardware.
Quick Check
Q: Why is catching a bug during simulation cheaper than catching it after fabrication?
Show Answer
Fabrication is a slow, expensive, physical process. A bug found in simulation only costs engineering time to fix and re-run. A bug found after fabrication may require a costly and time-consuming respin of the chip.
From Separate Languages to One
Design and verification used to rely on entirely separate languages. RTL was written in an HDL like Verilog or VHDL, while verification-focused languages like Vera and e were used to build testbenches around them. Maintaining a design in one language and its testbench in another added friction — different syntax, different tools, and no shared type system between the two.
SystemVerilog collapsed that gap by extending Verilog directly, the most widely used HDL, so both the design and its testbench can live in a single, consistent language. Its OOP support also makes it possible to build verification environments at a much higher level of abstraction than plain Verilog ever allowed, while its synthesizable additions do the same for RTL design.
Design and Verification Working Together
A hardware design typically consists of several Verilog or SystemVerilog files with one top module that instantiates all the sub-modules needed to implement the desired functionality. A testbench, usually written in SystemVerilog, is built around this design to verify it.
The design is instantiated inside the testbench, and its input/output ports are connected to testbench signals. Specific values are driven onto the design's inputs, and the resulting outputs are compared against expected values to confirm the design behaves correctly.
Click here to read more on a SystemVerilog TestBench !
Example: Why SystemVerilog Helps — A Traffic Light Controller
A common design pattern is a state machine that cycles through a fixed set of states — here, a traffic light cycling RED → GREEN → YELLOW → RED. In plain Verilog, states are usually tracked with hand-picked binary numbers:
// File : traffic_light.v
module traffic_light (
input clk, rst,
output reg [1:0] state
);
parameter RED = 2'b00, GREEN = 2'b01, YELLOW = 2'b10;
always @ (posedge clk) begin
if (rst)
state <= RED;
else case (state)
RED : state <= GREEN;
GREEN : state <= YELLOW;
YELLOW : state <= RED;
endcase
end
endmodule
This code is correct, but it has a maintenance problem: RED, GREEN, and YELLOW are just numbers you assigned by hand. Nothing stops two states from accidentally sharing the same value in a larger FSM, and when you trace state in a waveform viewer, you'll see 2'b00, 2'b01, 2'b10 instead of readable names.
Here's the same design in SystemVerilog:
// File : traffic_light_sv.sv
typedef enum logic [1:0] {RED, GREEN, YELLOW} state_t;
module traffic_light_sv (
input logic clk, rst,
output state_t state
);
always_ff @ (posedge clk) begin
if (rst)
state <= RED;
else case (state)
RED : state <= GREEN;
GREEN : state <= YELLOW;
YELLOW : state <= RED;
endcase
end
endmodule
The functional behavior is identical, but three real, verifiable benefits come from just the state_t declaration:
- No hand-picked encoding:
typedef enumassigns each member a unique value automatically, so there's no way for RED and YELLOW to accidentally collide the way two hand-written parameters could in a larger design. - Readable waveforms: a waveform viewer displays RED, GREEN, and YELLOW by name instead of raw binary, which makes debugging noticeably faster.
- Real type safety: since state is declared as state_t, assigning it a raw value outside {RED, GREEN, YELLOW} (like
state = 2'b11;) requires an explicit cast — the compiler catches an invalid state assignment instead of letting it slip into simulation.
Enum variables also come with a built-in .name() method that returns the current state as a string — useful for $display messages without writing your own lookup logic.
always_ff adds a smaller, complementary benefit: it documents that this block is meant to be sequential only, so tools that check design intent are more likely to flag a mistake (like a stray blocking assignment) as an error or warning instead of letting it pass silently.
Both versions still connect to a testbench the same way — instantiate the module, drive clk/rst from the testbench, and observe state, exactly as described earlier in this article.
Common Beginner Mistakes
Mistake #1: Hand-assigning state encodings as a design grows.
In traffic_light.v, RED, GREEN, and YELLOW are manually numbered. As more states get added over time, it's easy to reuse a value by accident — a bug typedef enum removes by assigning encodings automatically.
Mistake #2: Defining an enum type inside a module but trying to use it in that module's own port list.
Port declarations need any custom type to already be visible, so state_t is defined before traffic_light_sv in the example above. In real projects, this typically lives in a shared package instead so multiple files can reuse the same type.
Mistake #3: Assuming SystemVerilog is only a verification language.
Constructs like always_ff, logic, and enum are fully synthesizable and are increasingly used to write RTL design code, not just testbenches — as shown by traffic_light_sv above.
Practice Exercise
Challenge 1: Add a Safety State
Insert a brief ALL_RED state between YELLOW and RED in traffic_light_sv, so all lights are red for one cycle before the sequence restarts. Notice how little you need to change compared to renumbering every hand-picked parameter in the plain Verilog version.
Hint
Add ALL_RED to the typedef enum list, then update the case statement so YELLOW transitions to ALL_RED, and ALL_RED transitions to RED.
Solution
typedef enum logic [1:0] {RED, GREEN, YELLOW, ALL_RED} state_t;
// Rest of the module is unchanged - only the case statement below differs
else case (state)
RED : state <= GREEN;
GREEN : state <= YELLOW;
YELLOW : state <= ALL_RED;
ALL_RED : state <= RED;
endcase
Only the enum list and the case statement changed — no encoding values to renumber, since typedef enum assigns them automatically.
Challenge 2: Write a Testbench for the Controller
Write a short SystemVerilog testbench that instantiates traffic_light_sv, generates a clock, pulses rst, and prints the state name each cycle.
Hint
Declare a state_t signal to connect to the design's output port, and use its built-in .name() method inside $display to print readable state names instead of raw bits.
Solution
module tb_traffic_light ();
logic clk, rst;
state_t state;
traffic_light_sv dut (.clk(clk), .rst(rst), .state(state));
always #10 clk = ~clk;
initial begin
clk = 0; rst = 1;
#20 rst = 0;
repeat (4) begin
@ (posedge clk);
$display("time=%0t state=%s", $time, state.name());
end
end
endmodule
The structure mirrors the general design-verification pattern described earlier — instantiate, drive inputs, then observe an output — with .name() turning the enum value straight into a readable label.
Summary
In this tutorial, you learned:
- SystemVerilog is a superset of Verilog used for both RTL design (synthesizable constructs like
always_ff,enum) and verification (OOP, randomization, coverage, assertions) - Verilog alone lacks the expressiveness for modern RTL design and the features needed to efficiently verify large, complex designs
- Verification confirms a design behaves correctly before costly fabrication, avoiding respins
- SystemVerilog unified what used to be separate design (HDL) and verification (HVL) languages into one
- A testbench instantiates the design, drives its inputs, and checks its outputs against expected values
Quiz
No quiz questions available for this article.