System Verilog provides the foreach loop as a convenient way to iterate through arrays and multi-dimensional arrays. Unlike traditional loops like for, which require explicit index management, the foreach loop simplifies the process by automatically iterating over each element of an array. This feature is especially useful in verification environments and hardware modeling where array operations like dynamic, associative, and multi-dimensional arrays are common.
Syntax:
foreach (array_name[index]) begin
// Code block using array_name[index]
end
array_name: The name of the array to iterate over.index: The loop variable representing the current index.
Example 1: Iterating Over a One-Dimensional Array
module foreach_example1;
logic [7:0] arr [0:9]; // Declare an array of 10 elements
initial begin
// Initialize the array with values equal to their indices
foreach (arr[i]) begin
arr[i] = i;
end
// Use foreach to display the array values
foreach (arr[i]) begin
$display("arr[%0d] = %0d", i, arr[i]);
end
end
endmodule
arr[0] = 0
arr[1] = 1
arr[2] = 2
arr[3] = 3
arr[4] = 4
arr[5] = 5
arr[6] = 6
arr[7] = 7
arr[8] = 8
arr[9] = 9
Example 2: Iterating Over a Multi-Dimensional Array
module foreach_example2;
logic [3:0] matrix [0:2][0:2]; // Declare a 3x3 matrix
initial begin
// Initialize the matrix
foreach (matrix[i, j]) begin
matrix[i][j] = i * j; // Set each element to row*column
end
// Display the matrix
foreach (matrix[i, j]) begin
$display("matrix[%0d][%0d] = %0d", i, j, matrix[i][j]);
end
end
endmodule
Explanation:
- The
foreachloop uses multiple indices (iandj) to iterate over the rows and columns of the matrix. - This simplifies handling of multi-dimensional arrays without needing nested loops.
matrix[0][0] = 0
matrix[0][1] = 0
matrix[0][2] = 0
matrix[1][0] = 0
matrix[1][1] = 1
matrix[1][2] = 2
matrix[2][0] = 0
matrix[2][1] = 2
matrix[2][2] = 4
Example 3: Iterating Over Associative Arrays
module foreach_example3;
typedef int unsigned key_t;
typedef logic [7:0] value_t;
value_t assoc_array[key_t]; // Declare an associative array
initial begin
// Populate the associative array
assoc_array[1] = 8'hAA;
assoc_array[3] = 8'hBB;
assoc_array[5] = 8'hCC;
// Use foreach to iterate over the associative array
foreach (assoc_array[key]) begin
$display("assoc_array[%0d] = %h", key, assoc_array[key]);
end
end
endmodule
Explanation:
- The
foreachloop iterates over all valid keys in the associative array. - The loop variable
keyautomatically takes the value of each key in the array.
assoc_array[1] = aa
assoc_array[3] = bb
assoc_array[5] = cc
Features of the foreach Loop
- Automatic Index Management:
- The
foreachloop handles indices automatically, reducing the risk of off-by-one errors.
- The
- Supports All Array Types:
- Works seamlessly with fixed-size arrays, dynamic arrays, associative arrays, and queues.
- Multi-Dimensional Support:
- Simplifies operations on multi-dimensional arrays by handling multiple indices.