Poll

Do you like the discussion forum ?

SystemVerilog arrays are data structures that allow storage of many values in a single variable. A foreach loop is only used to iterate over such arrays and is the easiest and simplest way to do so.

Syntax

The foreach loop iterates through each index starting from 0. If there are multiple statements within the foreach loop, they have to be enclosed with begin and end keywords like all other procedural blocks.

 
  foreach(<variable>[<iterator>])
    // Single statement
 
  foreach(<variable>[<iterator>]) begin
    // Multiple statements
  end
 

Example #1: Single dimensional Arrays

 
module tb;
  int array[5] = '{1, 2, 3, 4, 5};
  int sum;
 
  initial begin
    // Here, "i" is the iterator and can be named as anything you like
    // Iterate through each element from index 0 to end using a foreach
    // loop.
    foreach (array[i])
      $display ("array[%0d] = %0d", i, array[i]);
 
    // Multiple statements in foreach loop requires begin end
    // Here, we are calculating the sum of all numbers in the array
    // And because there are 2 statements within foreach there should
    // be a begin-end
    foreach (array[l_index]) begin
      sum += array[l_index];
      $display ("array[%0d] = %0d, sum = %0d", l_index, array[l_index], sum);
    end
  end
endmodule
 
Simulation Log
ncsim> run
array[0] = 1
array[1] = 2
array[2] = 3
array[3] = 4
array[4] = 5
array[0] = 1, sum = 1
array[1] = 2, sum = 3
array[2] = 3, sum = 6
array[3] = 4, sum = 10
array[4] = 5, sum = 15
ncsim: *W,RNQUIE: Simulation is complete.

Click to try this example in a simulator!   

Note that foreach is just a shorter version to the following for loop:

 
  for (int i = 0; i < $size(array); i++) begin
    // Statements inside the for loop
  end
 

Example #2: Multidimensional Arrays

 
module tb;
  int md_array [5][2] = '{'{1,2}, '{3,4}, '{5,6}, '{7,8}, '{9,10}};
 
  initial begin
      // First iterate through the first dimension using "i"
      foreach (md_array[i])
        // For each element in first dimension "i", iterate through the
        // second dimension using "j"
        foreach (md_array[i][j])
          $display("md_array[%0d][%0d] = %0d", i, j, md_array[i][j]);      
  end
endmodule
 
Simulation Log
ncsim> run
md_array[0][0] = 1
md_array[0][1] = 2
md_array[1][0] = 3
md_array[1][1] = 4
md_array[2][0] = 5
md_array[2][1] = 6
md_array[3][0] = 7
md_array[3][1] = 8
md_array[4][0] = 9
md_array[4][1] = 10
ncsim: *W,RNQUIE: Simulation is complete.

Click to try this example in a simulator!   

Click here to learn more about other loops in SystemVerilog !

You may also like:

You consent to our cookies if you continue to use our website. To know more about cookies, see our privacy policy. I accept cookies from this site.

Agree