HDL & Verification

Why does the code above create a latch, and what is the fix?

always @(*) begin
    case (sel)
        2'b00: y = a;
        2'b01: y = b;
        2'b10: y = c;
    endcase
end
  1. AThree inputs are used in the case; reduce them to two
  2. BNo value is assigned to y when sel = 2'b11; add a default clause so every case assigns a value
  3. Calways @(*) is used; change it to always @(posedge clk)
Show answer and explanation

Answer: B. No value is assigned to y when sel = 2'b11; add a default clause so every case assigns a value

sel is 2 bits with four possible values, but 2'b11 is not handled, so y must keep its previous value in that case, creating a latch. Specifying a value for every remaining case, such as "default: y = 0;", or assigning y a default value before the case statement yields combinational logic. Latches from incomplete conditions are a common mistake for HDL beginners.

  • A. The number of inputs is not the cause.
  • B. Correct. Every case must be covered.
  • C. That would create flip-flops, a different circuit.
Practice this topic Back to topic

More HDL & Verification questions

  1. Which coding style is commonly used to prevent unintended latches in combinational always blocks?
  2. Which Verilog construct is ignored by logic synthesis and does not become hardware (a simulation-only construct)?
  3. When the code above, which counts the 1s in 8-bit d, is synthesized, what kind of circuit results?
  4. What type of reset does the code above have, and how does it behave?
  5. What is the difference between synchronous and asynchronous resets?