VLSI DV Interview Puzzles · All levels
String Substr with Runtime Class Cast
Predict all outputs from string methods and both `$cast` attempts.
Puzzle
Difficulty: Easy · Puzzle 1 of 6 · Topic: String and Casting Puzzles
Predict all outputs from string methods and both `$cast` attempts.
Code
systemverilog
class base_pkt; endclass
class good_pkt extends base_pkt;
int id = 42;
endclass
class bad_pkt extends base_pkt; endclass
module p1;
string s = "dv puzzle";
base_pkt b1, b2;
good_pkt g;
initial begin
b1 = new good_pkt();
b2 = new bad_pkt();
$display("substr=%s", s.substr(3,8));
$display("toupper=%s", s.toupper());
if ($cast(g, b1)) $display("cast1 ok id=%0d", g.id);
else $display("cast1 fail");
if ($cast(g, b2)) $display("cast2 ok id=%0d", g.id);
else $display("cast2 fail");
end
endmoduleHint
`substr(i,j)` uses inclusive indices. `$cast` checks runtime object type, not just declared handle type.
Step-by-step solution
diagram
1) `substr(3,8)` on `"dv puzzle"` returns `"puzzle"` (index 3 through 8 inclusive).
2) `toupper()` returns `"DV PUZZLE"`.
3) `b1` points to `good_pkt`, so `$cast(g,b1)` succeeds and prints id 42.
4) `b2` points to `bad_pkt`, so cast to `good_pkt` fails.Answer
Answer: substr=puzzle, toupper=DV PUZZLE, cast1 ok id=42, cast2 fail
Why candidates get it wrong
Candidates confuse static type compatibility with dynamic runtime-type compatibility.
Interviewer follow-up
What happens to `g` after the failed second cast in this code?