Problems in Reading SV queue elements through foreach/for loop construct

Hi Friends,

In below example,While reading queue using either foreach and for loop,it won’t iterate through all the queue element, where as when i write queue reading logic inside repeat construct either with the hard coded value or queue_Size ,it reads properly. but not with foreach and for construct.



module queue_of_class_ex;

 class packet;
   static int UID =0;
   rand bit [2:0] temp1;
   rand byte temp2;

    function new;
      UID++;
    endfunction

   function void print ();
     $display("UID=%0d,temp1=%0d,temp2=%0d",UID,temp1,temp2);
   endfunction:print
 endclass

  packet txnh,txn_read;
  initial
    begin
      //declare queue of packet type
      packet txn_que[$];
          //txnh = new;
      repeat(5)
        begin
          txnh = new;
          assert(txnh.randomize())
          //txnh.print();
          else
            $error("Randomization failed");
            //Pushing randomized packet into queue to store it
            $display("Pushing Packet with ID=%0d into queue",txnh.UID);
            txn_que.push_back(txnh);
        end
         $display("Before Reading Packet from queue size=%0d",txn_que.size);
         //foreach(txn_que[que_size])
         for(int que_size =0;que_size < txn_que.size;que_size--)
            begin
                txn_read = txn_que.pop_front();
                txn_read.print();
                
            end
            // here after reading it through either foreach and for loop it
            // still shows the queue size 2 instead 0.
            $display("After reading,queue size become %0d",txn_que.size);

    end

    endmodule 

Thanks.

In reply to VLSI_ENTHU:

You should not modify the size of any array while iterating over it with a foreach loop. And you are running into similar problems. You can just do

txn_read = txn_que[que_size];

instead of popping it off the queue. Or you can use a while loop,

while(txn_que.size!=0)
   begin
     txn_read = txn_que.pop_front();
     txn_read.print();
   end