Looping Statements

While Statements

A while statement evaluates an expression and repeatedly executes the subsequent statement if the expression evaluates to true. For example:

ones = 0;
while (data) begin
   ones = ones + data[0];
   data = data >> 1;

This code counts the number of bits that are 1 in a number.

For Statements

The for statement is used to iterate through a range of values. For example:

for (i = 0; i < 64; i = i + 1)

This is equivalent to:

i = 0;
while (i < 64) begin
   i = i + 1;

Thus, ‘i = 0’ is acting as the initializer, ‘i < 64’ the conditional that indicates the loop should continue, and ‘i = i + 1’ the incrementer.

Repeat Statements

A repeat statement evaluates an expression and then executes the subsequent statement that many times. For example:

always @(posedge start) begin
   repeat (8) begin
       #1 out <= data[0];
       data = data >> 1;

Forever Statements

A forever statement executes the subsequent statement repeatedly forever. For this reason, the subsequent must contain something that will block execution, such as a delay statement, an event statement, or a blocking assignment statement with delay. For example:

initial wait (start) forever #5 clk = ~clk;

This code waits for start to become true, and then it generates a clock on clk with a period of 10.