Consider the following Verilog code snippet:
module latch_example(input wire clk, input wire en, input wire d, output reg q);
always @(posedge clk) begin
if (en)
q <= d;
end
endmoduleWhat is the behavior of the output q?
module latch_example(input wire clk, input wire en, input wire d, output reg q); always @(posedge clk) begin if (en) q <= d; end endmodule
Think about whether q is assigned in all cases inside the clocked block.
The code uses a clocked always block with a conditional assignment. Since q is assigned only when en is high, but the block is triggered only on clock edges, q holds its value otherwise naturally. This is a proper synchronous design and does not infer a latch.
Examine this Verilog code:
module latch_infer(input wire a, b, output reg y);
always @(*) begin
if (a)
y = b;
end
endmoduleWhat happens when this code is synthesized?
module latch_infer(input wire a, b, output reg y); always @(*) begin if (a) y = b; end endmodule
Check if y is assigned a value in every possible condition.
Since y is assigned only when a is true, but not assigned when a is false, the synthesizer infers a latch to hold the previous value of y. This is latch inference due to incomplete assignment in a combinational block.
Look at this Verilog code snippet:
module latch_bug(input wire a, b, output reg y);
always @(*) begin
if (a)
y = b;
end
endmoduleWhich fix will prevent latch inference?
module latch_bug(input wire a, b, output reg y); always @(*) begin if (a) y = b; end endmodule
Think about how to assign y in all cases inside the always block.
Adding an else clause ensures y is assigned in every possible path, preventing latch inference. Changing the sensitivity list or removing the if changes the design intent or causes errors. Declaring y as wire is invalid because y is assigned inside an always block.
In Verilog, why does latch inference happen when using always @(*) blocks?
Think about what happens if a variable is not assigned a value in every condition inside a combinational block.
Latches are inferred when a variable inside a combinational block is not assigned in all possible paths. The synthesizer infers storage (a latch) to hold the last value when no new assignment occurs. This is why complete assignments are necessary in combinational logic.
Given this Verilog code that infers a latch:
module latch_problem(input wire a, b, output reg y);
always @(*) begin
if (a)
y = b;
end
endmoduleRewrite the always block to avoid latch inference but keep the same behavior: y should be b when a is true, and 0 otherwise.
Make sure y is assigned in all paths inside the always block.
Option A adds an else clause assigning y = 0 when a is false, preventing latch inference and preserving the intended behavior. Option A is a continuous assignment and cannot assign to reg y. Option A changes the design to sequential logic. Option A changes y to wire and changes the design style.