Always vs forever in Verilog HDL

15.6k views Asked by At

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!

1

There are 1 answers

0
Jared Davis On BEST ANSWER

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.