SystemVerilog repeat and forever loop

repeat and forever loop

repeat loop

repeat will execute the statements within the loop for a loop variable number of times.

if the loop variable is N, then the statements within the repeat block will be executed N number of times.

repeat loop syntax

repeat(<variable>) begin
  //statement - 1
  ...
  //statement - n
end

statements 1-n will be executed for a variable value number of times.

repeat loop example

In the below example,
repeat loop value is 4, so the statements within the repeat loop will be executed for 4 times.

module repeat_loop;
  int a;
  initial begin
    $display("-----------------------------------------------------------------");

    repeat(4) begin
        $display("\tValue of a=%0d",a);
        a++;
     end
    $display("-----------------------------------------------------------------");
  end   
endmodule

Simulator Output

-----------------------------------------------------------------
Value of a=0
Value of a=1
Value of a=2
Value of a=3
-----------------------------------------------------------------

Click to execute on

forever loop

As the name says forever loop will execute the statements inside the loop forever.
It can be said as indefinite iteration.

forever loop syntax

forever begin
  //statement - 1
  ...
  //statement - n
end

forever loop example

module forever_loop;
  int a;
  initial begin
    $display("-----------------------------------------------------------------");
 
    forever begin
      $display("\tValue of a=%0d",a);
      a++;
      #5;
    end
 
    $display("-----------------------------------------------------------------");
  end
  initial begin
    #20 $finish;
  end   
endmodule

Simulator Output

-----------------------------------------------------------------
           Value of a=0
           Value of a=1
           Value of a=2
           Value of a=3
$finish called from file "testbench.sv", line 27.
$finish at simulation time                   20

Click to execute on

❮ Previous Next ❯