Printing the packed array elements using foreach loop

Hi All,

When i am tried to use foreach loop to print each elements of packed array, it is printing from MSB position to 0th position, instead of printing from 0th position to MSB. It is confusing (since foreach loop iteration element(“i”) starts from 0 and iterate till n-1. But in below code it starts from n-1 & ends at 0).

Anyone could please tell us the reason behind this



module test;
  bit[3:0] a;
    initial begin
      a=4'b1101;
      foreach(a[i])
        $display("i=%0d, a[%0d] = %0d",i,i,a[i]);
    end
endmodule


Simulator Output :

vsim -voptargs=+acc=npr

run -all

i=3, a[3] = 1

i=2, a[2] = 1

i=1, a[1] = 0

i=0, a[0] = 1

In reply to Tulasiram:

Section 12.7.3 of the LRM describes the behavior of foreach loops. Specifically, the foreach loop will iterate using the dimensions of the array as the start and end values. Since a is declared with ‘3:0’, the foreach loop will go from 3 down to 0.

If the array was declared as ‘bit[0:3] a’, the foreach loop would iterate from 0 to 3.