Ready-to-run snippets

Code Examples

Ready-to-run Verilog, SystemVerilog, and UVM examples. Click any to open it live in the IDE.

← All examples

$cast As A Function

SystemVerilog Classes & OOP

$cast used as a function - if ($cast(...)) - so an invalid value is reported and handled instead of erroring out.

Open in IDE
testbench.sv
typedef enum { PENNY=1, FIVECENTS=5, DIME=10, QUARTER=25, DOLLAR=100 } Cents;

module tb;
	Cents 	myCent;
	
	initial begin
		if ($cast (myCent, 75))
			$display ("Cast passed");
		else
			$display ("Cast failed");
		$display ("Money=%s", myCent.name());
	end
endmodule

/* 
Simulation Log:
---------------
ncsim> run
Cast failed
Money=
ncsim: *W,RNQUIE: Simulation is complete.
ncsim> exit
*/
design.sv
// Code your design here
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.