VLSI DV Interview Puzzles · All levels
Enum Safety with $cast
Predict cast success bits and enum value after each attempt.
Puzzle
Difficulty: Medium · Puzzle 4 of 6 · Topic: String and Casting Puzzles
Predict cast success bits and enum value after each attempt.
Code
systemverilog
typedef enum int {IDLE=0, BUSY=1, DONE=2} state_e;
module p4;
int raw1 = 2;
int raw2 = 3;
state_e s = IDLE;
initial begin
$display("c1=%0d s=%s", $cast(s, raw1), s.name());
$display("c2=%0d s=%s", $cast(s, raw2), s.name());
end
endmoduleHint
`$cast` to enum succeeds only for legal enumerator values. On failure, destination keeps previous value.
Step-by-step solution
diagram
1) `raw1=2` is legal enum value DONE, so first cast returns 1 and `s` becomes DONE.
2) `raw2=3` is not a legal enumerator, so second cast returns 0.
3) Failed cast does not modify destination, so `s` stays DONE.Answer
Answer: First line: c1=1 s=DONE; second line: c2=0 s=DONE
Why candidates get it wrong
People assume failed `$cast` zeroes destination or sets it to first enum literal.
Interviewer follow-up
How would a static cast `state_e'(raw2)` behave differently?