Verilog Looping statements

There are four types of looping statements. These statements provide a means of controlling the execution of a statement zero, one, or more times.

forever Continuously executes a statement.
repeat Executes a statement a fixed number of times. If the expression evaluates to unknown or
high impedance, it shall be treated as zero, and no statement shall be executed.
while Executes a statement until an expression becomes false. If the expression starts out false,
the statement shall not be executed at all.
for Controls execution of its associated statement(s) by a three-step process, as follows:
a) Executes an assignment normally used to initialize a variable that controls the number
of loops executed.
b) Evaluates an expression. If the result is zero, the for loop shall exit. If it is not zero,
the for loop shall execute its associated statement(s) and then perform step c). If the
expression evaluates to an unknown or high-impedance value, it shall be treated as
zero.
c) Executes an assignment normally used to modify the value of the loop-control variable,
then repeats step b).

forever statement
| repeat ( expression ) statement
| while ( expression ) statement
| for ( variable_assignment ; expression ; variable_assignment ) statement

Example 1Repeat statement: In the following example of a repeat loop, add and shift operators implement a multiplier:

parameter size = 8, longsize = 16;
reg [size:1] opa, opb;
reg [longsize:1] result;
begin : mult
      reg [longsize:1] shift_opa, shift_opb;
      shift_opa = opa;
      shift_opb = opb;
      result = 0;
      repeat (size) begin
      if (shift_opb[1])
         result = result + shift_opa;
         shift_opa = shift_opa << 1; shift_opb = shift_opb >> 1;
      end
end

Example 2While statement: The following example counts the number of logic 1 values in rega:

begin : count1s
     reg [7:0] tempreg;
     count = 0;
     tempreg = rega;
     while (tempreg) begin
     if (tempreg[0])
        count = count + 1;
        tempreg = tempreg >> 1;
    end
end

<< Previous | Next >>

Comments are closed.