How to Avoid Latches in Verilog: Causes and Fixes
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.
module latch_example(input wire a, b, output reg y);
always @(*) begin
if (a) begin
y = b;
end
// Missing else branch causes latch
end
endmoduleThe 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.
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
endmodulePrevention
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.