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

Randomization: Always Check the Return Value

SystemVerilog Randomization

Runnable example from the SystemVerilog Randomization tutorial (Always Check the Return Value)

Open in IDE
testbench.sv
class myPacket;
  rand bit [1:0] mode;
  constraint c_mode { mode < 3; }   // mode can only be 0, 1, or 2
endclass

module tb_top;
  myPacket pkt;

  initial begin
    pkt = new();

    // Effective pattern: branch on the return value instead of trusting it blindly
    if (pkt.randomize()) begin
      $display("Randomization OK   -> mode = %0d", pkt.mode);
    end else begin
      $display("Randomization FAIL -> mode unchanged, still = %0d", pkt.mode);
    end

    // mode == 5 can never satisfy c_mode (mode < 3), so this call is
    // guaranteed to fail - a deliberate example of a caught failure
    if (pkt.randomize() with { mode == 5; }) begin
      $display("Randomization OK   -> mode = %0d", pkt.mode);
    end else begin
      $display("Randomization FAIL -> mode unchanged, still = %0d", pkt.mode);
    end
  end
endmodule
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.