Queue


module queue;
  int q[$];
  initial begin
  q={1,2,3,4};
    $display("queue=%p",q);
 
    foreach(q[i])begin
    q.pop_back();
      $display("pop_back values =%p",i,q);
  end
  end
endmodule

Output:

# KERNEL: queue='{1, 2, 3, 4}
# KERNEL: pop_back values= '{1, 2, 3}
# KERNEL: pop_back values= '{1, 2}
# KERNEL: Simulation has finished. There are no more test vectors to simulate.

Doubts:
1.Why I can’t able to pop_back all the values in queue?
2.How to get the pop_back values in a queue again?
I need to get q1={4,3,2,1}.How to get this?

In reply to Design Engineer:

  1. Pop operation reduces the queue size by 1 in each iteration. Foreach loop is similar to repeat loop. At start your queue size is 4 so there should be 4 iterations.
    1st iteration → q.size=3 iteration_completed=1
    2nd iteration → q.size=2 iteration_completed=2
    After this iteration you have q.size and iteration_completed equal value so foreach loop stops.

A better approach to pop all items would be-


module queue;
int q[$];
int item;  

  initial begin 
    q={1,2,3,4}; 
    $display("queue=%p",q); 
    
    //foreach(q[i])begin 
    while(q.size>0)begin // Better approach to pop all elements
      item = q.pop_back(); 
      //$display("pop_back values =%p",i,q); 
      $display("popped_item=%0d ,remaining q=%p",item,q); 
    end  
  end
endmodule


  1. For reversing you can use -

  int q[$],q1[$]
  q.reverse;
  q1=q;
// or
 q1 = {<<32{q}};

In reply to verif4life:

If the dimensions of a dynamically sized array are changed while iterating over a foreach-loop construct, the results are undefined and may cause invalid index values to be generated.

In reply to dave_59:

Thanks for the correction Dave. I previously understood that quote from LRM as only for multi dimensional array cases, where number of dimensions get changed while iterating over foreach loop.

Thanks for ur help @ verif4life @Dave

I need to clarify my question 2 here,

Qn2: I need to store the pop_back values from each iteration in a single queue,How to do that?

In reply to Design Engineer:

I think it would serve you better if you tried to attempt it yourself.

why you want to do pop_back? you can simply use q.reverse() to reverse entire queue.

In reply to juhi_p:

why you want to do pop_back? you can simply use q.reverse() to reverse entire queue.

Because it is a homework/interview question.