Always vs forever in Verilog HDL

ellekaie picture ellekaie · Nov 28, 2014 · Viewed 9.6k times · Source

What are the difference between the always keyword (not the always @ block) and forever keyword in Verilog HDL?

always #1 a=!a;
forever #1 a=!a;

Here are my findings but I can't still quite draw the line between the two:

From Wikipedia:

The always keyword acts similar to the "C" construct while(1) {..} in the sense that it will execute forever.

From electroSofts:

The forever instruction continuously repeats the statement that follows it. Therefore, it should be used with procedural timing controls (otherwise it hangs the simulation).

Could someone give a clearer explanation on this? Thank you!

Answer

Jared Davis picture Jared Davis · Nov 28, 2014

The always construct can be used at the module level to create a procedural block that is always triggered. Typically it is followed by an event control, e.g., you might write, within a module, something like:

  • always @(posedge clk) <do stuff>

  • always @(en or d) <do stuff>

  • always @* <do stuff>, can also use @(*)

This is the typical way to write latches, flops, etc.

The forever construct, in contrast, is a procedural statement that should typically only be used in test-bench code. It can occur within always and initial blocks and other statements, but cannot occur directly within a module. For instance, you can use it to write things like:

initial begin
  if (do_random_testing)
  begin
    forever #100 input = $random(...);
  end
  else if (read_from_file)
  begin
     ... read inputs from a file or whatever ...
  end
end

It wouldn't be legal to write something like forever #1 a=!a; as a top-level construct in a module. It has to be put, e.g., in an always block, an initial block, a task, or similar.