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

Dynamic Array Randomization

SystemVerilog Randomization

How to randomize a dynamic array. Note : Verilator fails to handle this code properly ! But it works on commercial grade simulators like Xcelium, VCS, etc.

Open in IDE
testbench.v
class Packet;
  rand bit [3:0] 	d_array []; 	// Declare a dynamic array with "rand"

  // Constrain size of dynamic array between 5 and 10
  constraint c_array { d_array.size() > 5; d_array.size() < 10; }

  // Constrain value at each index to be equal to the index itself
  constraint c_val   { foreach (d_array[i])
    					d_array[i] == i;
                     }

  // Utility function to display dynamic array contents
  function void display();
    foreach (d_array[i])
      $display ("d_array[%0d] = 0x%0h", i, d_array[i]);
  endfunction
endclass

module tb;
  Packet pkt;

  // Create a new packet, randomize it and display contents
  initial begin
    pkt = new();
    pkt.randomize();
    pkt.display();
  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.