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

forever loop: Stopping a forever Loop

SystemVerilog Control Flow & Loops

Runnable example from the SystemVerilog forever loop tutorial (Stopping a forever Loop)

Open in IDE
testbench.sv
module tb;
  bit clk, done;
  int cycles;

  always #5 clk = ~clk;          // clock rises at 5, 15, 25 ... ns
  initial #73 done = 1;          // some other process signals completion

  initial begin
    forever begin
      @(posedge clk);
      cycles++;
      if (done) break;           // leave the loop on the first edge after done
    end
    // Runs only after break: prints "Loop exited after 8 cycles at 75"
    $display ("Loop exited after %0d cycles at %0t", cycles, $time);
    $finish;
  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.