How to Use If Else in Verilog: Syntax and Examples
In Verilog, use
if and else inside procedural blocks like always to control logic flow based on conditions. The if checks a condition, and else runs code when the condition is false.Syntax
The if else statement in Verilog is used inside procedural blocks such as always or initial. The syntax is:
if (condition): Executes the following statement if the condition is true.else: Executes the following statement if theifcondition is false.
Conditions are expressions that evaluate to true or false (non-zero or zero).
verilog
always @(posedge clk) begin
if (condition) begin
// code when condition is true
end else begin
// code when condition is false
end
endExample
This example shows a simple 1-bit register that sets q to 1 if set is high, otherwise clears q to 0.
verilog
module if_else_example(
input wire clk,
input wire set,
output reg q
);
always @(posedge clk) begin
if (set) begin
q <= 1'b1;
end else begin
q <= 1'b0;
end
end
endmoduleCommon Pitfalls
Common mistakes when using if else in Verilog include:
- Forgetting to use
beginandendwhen multiple statements followiforelse. - Using blocking assignments (
=) instead of non-blocking (<=) inside sequentialalwaysblocks. - Not covering all conditions, which can cause inferred latches.
verilog
/* Wrong: Missing begin-end for multiple statements */ always @(posedge clk) begin if (set) q <= 1'b1; flag <= 1'b0; // This runs always, not only if set is true else q <= 1'b0; end /* Correct: Use begin-end to group statements */ always @(posedge clk) begin if (set) begin q <= 1'b1; flag <= 1'b0; end else begin q <= 1'b0; end end
Quick Reference
Tips for using if else in Verilog:
- Use
if elseinsidealwaysorinitialblocks only. - Use non-blocking assignments (
<=) for sequential logic. - Always use
beginandendfor multiple statements. - Cover all conditions to avoid unintended latches.
Key Takeaways
Use if else inside procedural blocks like always or initial in Verilog.
Always group multiple statements with begin and end after if or else.
Use non-blocking assignments (<=) for sequential logic inside always blocks.
Cover all conditions to prevent unintended latch inference.
Conditions in if statements must evaluate to true (non-zero) or false (zero).