Spot the Latch (Debug)
beginner · combinational · 55 XP
Sign in to write your solution, run it in the simulator and submit it for grading.
Sign in or create a free account →Problem
Spot the Latch (Debug Problem)
The following module has a bug — it infers a latch. Find it and fix it.
**Buggy Code:**
```verilog
module priority_enc_buggy (
input [3:0] req,
output reg [1:0] grant
);
always @(*) begin
if (req[3]) grant = 2'd3;
else if (req[2]) grant = 2'd2;
else if (req[1]) grant = 2'd1;
// BUG: no final else — latch inferred for req=4'b0001 and req=4'b0000
end
endmodule
```
**Your task:** Implement a **fixed** version called `priority_enc_fixed` that:
- Correctly encodes the highest-priority active request (MSB = highest)
- Has no latches (grant gets a value on every possible input)
- Outputs `grant=2'd0` and `valid=1` when `req[0]` is the only active bit
- Outputs `grant=2'd0` and `valid=0` when `req=4'b0000`
**Interface**
| Port | Direction | Width | Description |
|------|-----------|-------|-------------|
| `req[3:0]` | input | 4 | Request lines |
| `grant[1:0]` | output | 2 | Encoded grant |
| `valid` | output | 1 | High when any request active |
Constraints
- Add a default assignment at the top of the always block.
- valid must be high when any req bit is set.
- No latch — grant must be assigned on all paths.
Examples
Input: req=4'b1010
Output: grant=2, valid=1
Input: req=4'b0000
Output: grant=0, valid=0
Common questions
- What does the Spot the Latch (Debug) problem ask you to build?
- Spot the Latch (Debug Problem) The following module has a bug — it infers a latch. Find it and fix it.
- What constraints does Spot the Latch (Debug) have?
- Add a default assignment at the top of the always block.; valid must be high when any req bit is set.; No latch — grant must be assigned on all paths.
- What is an example input and output for Spot the Latch (Debug)?
- Input req=4'b1010 gives output grant=2, valid=1.
- Which Verilog concepts does Spot the Latch (Debug) practise?
- combinational, debug, latch, interview, always.