SystemVerilog repeat and forever loop

repeat and forever loop


repeat loop


repeat will executes the statements with in the loop for a loop variable number of times.
if loop variable is N, then the statements with in 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 below example repeat loop value is 4, so the statements with in 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
     -----------------------------------------------------------------
Execute the above code on 



forever loop


As the name says forever loop will executes the statements inside the loop for 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
Execute the above code on