SystemVerilog foreach loop

foreach loop

SystemVerilog foreach specifies iteration over the elements of an array. the loop variable is considered based on elements of an array and the number of loop variables must match the dimensions of an array.

foreach loop syntax

foreach(<variable>[<iterator>]]) begin
  //statement - 1
  ...
  //statement - n
end

Foreach loop iterates through each index starting from index 0.

foreach loop example

below example shows,
foreach loop in the single dimensional array.

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

Simulator Output

-----------------------------------------------------------------
Value of a[0]=0
Value of a[1]=1
Value of a[2]=2
Value of a[3]=3
-----------------------------------------------------------------

Click to execute on

foreach multidimensional array

Below example shows how to use the foreach loop in a multidimensional array.

module for_loop;
  int a[3][2];

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

Simulator Output

-----------------------------------------------------------------
 Value of a[0][0]=0
 Value of a[0][1]=1
 Value of a[1][0]=1
 Value of a[1][1]=2
 Value of a[2][0]=2
 Value of a[2][1]=3
-----------------------------------------------------------------

Click to execute on

❮ Previous Next ❯