Menu
Coddy logo textTech

Forever Loop

Part of the Fundamentals section of Coddy's Verilog journey — lesson 61 of 90.

The forever loop repeats a block of code continuously, forever. It never stops on its own.

A forever loop executes repeatedly without end. It is useful for generating clocks and other continuous signals in testbenches.

Syntax:

forever begin
  // Code that repeats forever
end

Simple Example

forever begin
  $display("This prints forever");
end

This will print endlessly and crash your simulation. Always add a delay or a stopping condition.

Generating a Clock (Common Use)

The most common use of forever is to generate a clock:

initial begin
  clk = 0;
  forever begin
    #5 clk = ~clk;   // Toggle every 5 time units
  end
end

This creates a clock that runs for the entire simulation.

Forever with Disable

You can stop a forever loop using a disable statement:

initial begin : clock_gen   // Name added here
  clk = 0;
  forever begin
    #5 clk = ~clk;
  end
end
initial begin
  #100;
  disable clock_gen;   // Now this works
end

Forever vs Other Loops

LoopStops?When to Use
forYes (after fixed iterations)Known number of repeats
whileYes (when condition false)Unknown stop condition
repeatYes (after fixed iterations)Known number of repeats
foreverNo (never)Continuous signals (clock)

Important Rules

RuleExplanation
Must include a delay#10 or @(posedge clk)
Without delay, simulation hangsInfinite loop with no time advance
Use with disable to stopOr simulation never ends
Best used in testbenchesNot synthesizable
challenge icon

Challenge

What to do:

Add the missing forever loop to generate a clock that toggles every 10 time units.

Cheat sheet

The forever loop repeats a block of code continuously without stopping. Always include a delay to prevent simulation hang.

initial begin
  clk = 0;
  forever begin
    #5 clk = ~clk; // Toggle every 5 time units
  end
end

Stop a forever loop using disable with a named block:

initial begin : clock_gen
  clk = 0;
  forever begin
    #5 clk = ~clk;
  end
end

initial begin
  #100;
  disable clock_gen;
end

Key rules:

  • Must include a delay (#10 or @(posedge clk)), otherwise simulation hangs
  • Use disable to stop, or simulation never ends
  • Not synthesizable — testbench use only

Try it yourself

module forever_challenge;
  reg clk;
  
  initial begin
    clk = 0;
    // TODO: Add forever loop to toggle clk every 10 time units
  end
endmodule
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals