Electronic – How to fill a SystemVerilog Queue variable

hdlsystem-verilogverilog

module queues;
int a[$];

int i = 100;

initial begin
    foreach(a[i]) a[i] = i;
    foreach(a[i]) $display("\tValue of a[%0d]=%0d",i,a[i]);
end
endmodule

I have my unbounded queue 'a'. I have to fill > 150 locations with random data. I have to use (push/pop/positional) constructs as well. I am trying to fill some of the positions using for/foreach loop, but it's not working.

Error msg: XXXX: I don't know how to handle expr_type=9 here error:
Code generation had 1 error(s).

Where am I wrong? And what do you suggest to do in this problem statement?

Best Answer

When I run your code on my simulators, I don't get any error message. But, I also don't see any of the display messages either. That is expected because neither of your foreach loops executes. Since the queue is empty, the 1st foreach loop has nothing to loop over. Therefore, nothing is added to the queue. Similarly for the 2nd foreach.

You can use a for loop to add to the queue:

module queues;

int a[$];

initial begin
    for (int i=0; i<100; i++) a.push_back(i);
    foreach(a[i]) $display("\tValue of a[%0d]=%0d",i , a[i]);
end
endmodule

This prints:

Value of a[0]=0
Value of a[1]=1
Value of a[2]=2
Value of a[3]=3
Value of a[4]=4
Value of a[5]=5

etc.

If you really want random data (as you mentioned), you could use something like $urandom:

for (int i=0; i<100; i++) a.push_back($urandom);