VLSI DV Interview Puzzles · All levels

Signed vs Unsigned Comparison Trap

What are the three outputs, and why does the first comparison surprise people?

Puzzle

Difficulty: Medium · Puzzle 2 of 6 · Topic: Datatype and Bit Puzzles

What are the three outputs, and why does the first comparison surprise people?

Code

systemverilog
module p2;
  logic signed [3:0] s = -1;
  logic [3:0] u = 4'h1;
  initial begin
    $display("s<u=%0d", s < u);
    $display("$signed(u)>s=%0d", $signed(u) > s);
    $display("s+u=%0d", s + u);
  end
endmodule

Hint

Mixed signed/unsigned expressions follow conversion rules before the operator executes. Also check expression width.

Step-by-step solution

diagram
1) In `s < u`, `u` is unsigned, so `s` is converted to unsigned 4'b1111 (15); 15 < 1 is false.
2) `$signed(u)` forces signed compare in second line: 1 > -1 is true.
3) `s + u` is still mixed signed/unsigned at 4-bit width: 15 + 1 wraps to 0.

Answer

Answer: s<u=0, $signed(u)>s=1, s+u=0

Why candidates get it wrong

People reason from mathematical values (-1 and 1) without first applying SV type-conversion rules.

Interviewer follow-up

If `u` were declared `logic signed [3:0]`, what would `s<u` and `s+u` become?

Related topics