0
0
VerilogDebug / FixBeginner · 3 min read

How to Avoid Latches in Verilog: Causes and Fixes

To avoid unintended latches in Verilog, always assign values to signals in every possible branch of your combinational always blocks. Missing assignments in some branches cause synthesis tools to infer latches to hold previous values, so use else clauses or default assignments to prevent this.
🔍

Why This Happens

Latches are inferred in Verilog when a signal inside a combinational always block is not assigned a value in all possible conditions. This makes the hardware remember the previous value, which is a latch. This often happens when if statements miss an else branch or when some conditions do not assign the signal.

verilog
module latch_example(input wire a, b, output reg y);
  always @(*) begin
    if (a) begin
      y = b;
    end
    // Missing else branch causes latch
  end
endmodule
Output
Warning: Latch inferred for signal 'y' because it is not assigned in all branches.
🔧

The Fix

To fix this, assign a default value to the signal at the start of the always block or add an else branch that assigns the signal. This ensures the signal is always assigned, so no latch is created.

verilog
module no_latch_example(input wire a, b, output reg y);
  always @(*) begin
    y = 1'b0; // default assignment
    if (a) begin
      y = b;
    end
  end
endmodule
Output
No latch inferred; 'y' is assigned in all conditions.
🛡️

Prevention

Always assign signals in every branch of combinational always blocks. Use default assignments at the start of the block to cover all cases. Use linting tools or simulators that warn about inferred latches. Writing clear and complete if-else or case statements helps avoid accidental latches.

⚠️

Related Errors

Similar errors include unintended flip-flops when clock edges are missed, or combinational loops causing simulation mismatches. These can be fixed by carefully reviewing signal assignments and clocking conditions.

Key Takeaways

Always assign signals in every branch of combinational always blocks to avoid latches.
Use default assignments at the start of the always block as a safe practice.
Lint your Verilog code to catch unintended latch inference early.
Complete if-else or case statements prevent accidental memory elements.
Unintended latches cause unpredictable hardware behavior and should be avoided.