Source – SV Verification Directory
For and Foreach Loops
Loops are essential constructs to repeat a block of code for a specified amount of time. SystemVerilog provides two constructs to itreate over a range of elements and they are “for” loop and “foreach” loop.
For Loop
Similar to other programming languages, the “for” loop in SystemVerilog repeats a block of code for a specified number of times. Ideal for controlled, indexed iterations where the number of iterations is known beforehand.
Syntax
for(initialization; condition; increment/decrement)begin
// execute the code
end
Example Code: For Loop
module for_loop;
initial begin
$display("---------- 3 Times Table ----------");
for(int i=0; i<11; i++)begin
$display("3 x %0d = %0d", i, 3*i);
end
end
endmodule
Execute the code in EDA Playground
Foreach Loop
The “Foreach” loop in SystemVerilog is specifically designed for iterating over arrays. It provides a simple and easy method to access each element in the array without the need of manipulating the index especially when dealing with dynamic or associative arrays.
Syntax
foreach (array[index]) begin
// execute the code
end
Example Code: Foreach
module foreach_loop;
int arr[ ];
initial begin
arr = new[16];
$display("---------- Initialize the Array ----------");
foreach(arr[i])begin
arr[i] = i;
end
foreach(arr[i])begin
$display("arr[%0d] = %0d", i, arr[i]);
end
end
endmodule