0
0
Verilogprogramming~5 mins

If-else in always blocks in Verilog

Choose your learning style9 modes available
Introduction

If-else statements inside always blocks help decide what the circuit should do based on conditions.

To choose between two or more actions depending on input signals.
To create simple decision-making logic like turning on a light if a switch is pressed.
To update outputs differently based on different input values.
To model behavior that changes over time or with events.
To handle reset conditions separately from normal operation.
Syntax
Verilog
always @(sensitivity_list) begin
    if (condition) begin
        // statements when condition is true
    end else begin
        // statements when condition is false
    end
end

The always block runs whenever signals in the sensitivity list change.

Use begin and end to group multiple statements inside if or else.

Examples
On clock's rising edge, if reset is true, set q to 0; otherwise, set q to d.
Verilog
always @(posedge clk) begin
    if (reset) begin
        q <= 0;
    end else begin
        q <= d;
    end
end
Whenever a or b changes, output the bigger value.
Verilog
always @(a or b) begin
    if (a > b) out = a;
    else out = b;
end
Sample Program

This module sets output q to 0 when reset is high at clock's rising edge. Otherwise, it copies input d to q.

Verilog
module simple_if_else(
    input wire clk,
    input wire reset,
    input wire d,
    output reg q
);

always @(posedge clk) begin
    if (reset) begin
        q <= 0;
    end else begin
        q <= d;
    end
end

endmodule
OutputSuccess
Important Notes

Use non-blocking assignments (<=) inside clocked always blocks for correct timing.

Always include all conditions to avoid unintended latches.

The sensitivity list controls when the always block runs; for clocked logic, use posedge or negedge.

Summary

If-else inside always blocks lets you choose actions based on conditions.

Use begin and end to group multiple statements.

Always blocks run when signals in their sensitivity list change.