For Loop
The for loop is a sequential statement that allows you to specify a fixed number of iterations in a behavioral design description. The following architecture demonstrates how a simple 8-bit parity generator can be described using a for loop:
library ieee;
use ieee.std_logic_1164.all;
entity parity10 is
port(D: in std_logic_vector(0 to 9);
ODD: out std_logic);
constant WIDTH: integer := 10;
end parity10;
architecture behavior of parity10 is
begin
process(D)
variable otmp: Boolean;
begin
otmp := false;
for i in 0 to D'length - 1 loop
if D(i) = '1' then
otmp := not otmp;
end if;
end loop;
if otmp then
ODD <= '1';
else
ODD <= '0';
end if;
end process;
end behavior;
The for loop includes an automatic declaration for the index (i in this example). You do not need to separately declare the index variable.
The index variable and values specified for the loop do not have to be numeric types and values. In fact, the index range specification does not even have to be represented by a range. Instead, it can be represented by a type or sub-type indicator. The following example shows how an enumerated type can be used in a loop statement:
architecture looper2 of my_entity is
type stateval is Init, Clear, Send, Receive, Error; -- States of a machine
begin
. . .
process(a)
begin
for state in stateval loop
case state is
when Init =>
...
when Clear =>
...
when Send =>
...
when Receive =>
...
when Error =>
...
end case;
end loop;
end process;
. . .
end looper2;
For loops can be given an optional name, as shown in the following example:
loop1: for state in stateval loop
if current_state = state then
valid_state <= true;
end if;
end loop loop1;
The loop name can be used to help distinguish between the loop index variable and other similarly-named objects, and to specify which of the multiple nested loops is to be terminated (see Loop Termination below). Otherwise, the loop name serves no purpose.
See also