0
0
Verilogprogramming~5 mins

Latch inference and how to avoid it in Verilog

Choose your learning style9 modes available
Introduction

Latch inference happens when your code accidentally creates memory elements you did not want. This can cause unexpected behavior in your digital circuit.

When designing digital circuits that need to store values only under certain conditions.
When you want to understand why your synthesis tool created latches instead of flip-flops.
When debugging unexpected circuit behavior caused by unintended memory elements.
When writing combinational logic and want to avoid accidental memory storage.
When learning how to write clear and safe Verilog code for hardware design.
Syntax
Verilog
always @(*) begin
  if (condition) begin
    output_signal = input_signal;
  end
  // missing else branch
end

Latch inference often happens when an always block does not assign a value to an output in all possible cases.

To avoid latches, always assign default values or cover all conditions with else branches.

Examples
This code avoids latch inference by assigning out in both if and else cases.
Verilog
always @(*) begin
  if (enable) begin
    out = in;
  end else begin
    out = 0;
  end
end
Here, a default value is assigned first, so out always has a value, preventing latch inference.
Verilog
always @(*) begin
  out = 0; // default assignment
  if (enable) begin
    out = in;
  end
end
This is a clocked block creating a flip-flop, so no latch is inferred.
Verilog
always @(posedge clk) begin
  if (reset) begin
    out <= 0;
  end else begin
    out <= in;
  end
end
Sample Program

This code will cause latch inference because out is not assigned when enable is false.

To fix it, add an else branch or a default assignment.

Verilog
module latch_example(
  input wire enable,
  input wire in,
  output reg out
);

  always @(*) begin
    if (enable) begin
      out = in;
    end
    // no else branch here causes latch inference
  end
endmodule
OutputSuccess
Important Notes

Always assign outputs in every possible path inside combinational always blocks.

Use default assignments at the start of the block to avoid missing assignments.

Latch inference can cause timing and functional bugs in your hardware design.

Summary

Latch inference happens when outputs are not assigned in all cases inside combinational blocks.

To avoid latches, use default assignments or cover all conditions with else branches.

Understanding latch inference helps you write safer and more predictable Verilog code.