Ready-to-run snippets

Code Examples

Ready-to-run Verilog, SystemVerilog, and UVM examples. Click any to open it live in the IDE.

← All examples

foreach loop: Iteration Order

SystemVerilog Control Flow & Loops

Runnable example from the SystemVerilog foreach loop tutorial (Iteration Order)

Open in IDE
testbench.sv
module tb;
  bit [3:0] nibble = 4'b0110;   // packed vector, declared [3:0]
  int       arr [3:0];          // unpacked array, declared high-to-low

  initial begin
    foreach (nibble[i])          // i = 3, 2, 1, 0
      $display ("nibble[%0d] = %0b", i, nibble[i]);

    foreach (arr[i])             // i = 3, 2, 1, 0
      $display ("arr index %0d", i);
  end
endmodule
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.