Gotcha: Using “rand” Modifier for Object Handles is not enough!

SystemVerilog allows rand modifier to be used for object handles and the object will be randomized only if it is not null.

The “gotcha” is that, depending on the simulator, no error or warning will be issued if you forget to initialize the randomized object.

Here is an example that illustrates the gotcha:

class item;
  rand int size;

class node;
  rand item item_1;
  rand item item_2;

  function new();
    item_2= new();

  function void post_randomize();
    $display($psprintf("item_1 is %p.", item_1));
    $display($psprintf("item_2 is %p.", item_2));

module top;
  initial begin
    automatic node a_node = new();

The output is:

item_1 is '{null}.
item_2 is '{size:-1424717967}

This behavior is useful in case you want to avoid generation of objects: leave the object handles uninitialized and their generation will not be triggered.
However, in the majority of the cases, when you mark an object with “rand” modifier you do expect to see a randomized instance of it after every call of randomize() method.

Keep in mind that rand modifier is not sufficient for the objects members of a class to be generated, they also have to be initialized prior to randomization.


Leave a Comment:

Your comment will be visible after approval.

(will not be published)

This site uses Akismet to reduce spam. Learn how your comment data is processed.