The if-else statement is a fundamental conditional construct in SystemVerilog, widely used in hardware description and verification. It allows designers to implement decision-making logic based on specific conditions. In addition to if-else, SystemVerilog introduces features like else if for cascading conditions and unique if for improved simulation and synthesis efficiency.
This article explains these constructs with examples to help you effectively use them in your designs.
Basics of if-else
The if-else statement evaluates a condition and executes corresponding code blocks based on whether the condition is true or false. The begin and end are required if we are using multiple statements in if-else block.
Syntax
if (condition)
statement_or_block;
else
statement_or_block;
else if for Cascading Conditions
When multiple conditions need to be evaluated in a sequence, the else if construct is used. It avoids deeply nested if-else structures and improves code readability.
Syntax
if (condition1)
statement_or_block1;
else if (condition2)
statement_or_block2;
else
statement_or_block_default;
Nested if-else Statements
A nested if-else statement occurs when an if or else block contains another if-else construct. This nesting helps in evaluating conditions in a hierarchical manner, where the outcome of one condition determines which subsequent conditions are evaluated.
Syntax
if (condition1) begin
if (condition2) begin
// Code block for condition1 and condition2 true
end else begin
// Code block for condition1 true and condition2 false
end
end else begin
// Code block for condition1 false
end
Example:
module else_if_example(sel,out);
input logic [1:0] sel;
output logic out;
always_comb begin
if (sel == 2'b00)
out = 1'b0;
else if (sel == 2'b01)
out = 1'b1;
else if (sel == 2'b10)
out = 1'b0;
else
out = 1'bz; // Default value for invalid cases
end
endmodule
Testbench:
module tb;
logic[1:0] sel;
logic out;
else_if_example dut(sel,out);
initial begin
sel = 2'b01;
#10 sel = 2'b10;
#10 sel = 2'b00;
end
initial begin
$monitor("sel = %0b, out = %0b",sel,out);
end
endmodule
Output:
sel = 1, out = 1
sel = 10, out = 0
sel = 0, out = 0
System Verilog unique if
The unique if construct is a System Verilog enhancement that improves efficiency by declaring that only one condition in the sequence can be true.
- The
uniquekeyword ensures that only oneiforelse ifcondition is true at a time. - If multiple conditions are true or none are true, the simulator issues a warning, which helps catch bugs early.
Example:
module unique_if_example;
initial begin
int a, b;
a = 30;
b = 40;
unique if(a > b)
$display("a is greater than b");
else if (20>b)
$display("20 is greater than b");
end
endmodule
Output:
Warning-[RT-NCMUIF] No condition matches in statement
testbench.sv, 9
No condition matches in 'unique if' statement. 'else' statement is missing
for the last 'else if' block, inside unique_if_example.unnamed$$_0, at time
0ns.
