0
0
VhdlHow-ToBeginner · 4 min read

How to Use For Loop in VHDL: Syntax and Examples

In VHDL, a for loop is used to repeat a block of code a fixed number of times, iterating over a range of values. It is written as for variable in range loop ... end loop; and is commonly used in processes or generate statements for hardware description.
📐

Syntax

The for loop in VHDL repeats statements for each value in a specified range. It has three main parts:

  • variable: loop counter variable
  • range: the set of values the variable takes (e.g., 0 to 7)
  • loop body: statements executed each iteration

The loop ends with end loop;.

vhdl
for i in 0 to 7 loop
    -- statements here
end loop;
💻

Example

This example shows a process that uses a for loop to assign values to an 8-bit vector, setting each bit to '1'.

vhdl
library ieee;
use ieee.std_logic_1164.all;

entity for_loop_example is
    port (
        clk : in std_logic;
        out_vector : out std_logic_vector(7 downto 0)
    );
end for_loop_example;

architecture Behavioral of for_loop_example is
    signal temp_vector : std_logic_vector(7 downto 0);
begin
    process(clk)
    begin
        if rising_edge(clk) then
            for i in 0 to 7 loop
                temp_vector(i) <= '1';
            end loop;
        end if;
    end process;
    out_vector <= temp_vector;
end Behavioral;
⚠️

Common Pitfalls

Common mistakes when using for loops in VHDL include:

  • Using a loop variable outside its scope (the variable only exists inside the loop).
  • Incorrect range direction (e.g., using 0 to 7 when the vector is 7 downto 0).
  • Trying to use loops for variable-length iterations (VHDL loops must have fixed ranges).

Always ensure the loop range matches the signal or array indexing direction.

vhdl
wrong:
for i in 0 to 7 loop
    signal_vector(i) <= '1'; -- if signal_vector is 7 downto 0, this mismatches
end loop;

right:
for i in signal_vector'range loop
    signal_vector(i) <= '1';
end loop;
📊

Quick Reference

ElementDescriptionExample
forStarts the loopfor i in 0 to 3 loop
variableLoop counter variablei
rangeValues variable takes0 to 3 or 7 downto 0
loop bodyStatements repeatedsignal(i) <= '1';
end loop;Ends the loopend loop;

Key Takeaways

Use for loop to repeat code for a fixed range of values in VHDL.
Loop variable scope is limited to inside the loop only.
Match the loop range direction with the signal or array indexing.
Use for i in signal'range loop to avoid indexing errors.
VHDL loops must have fixed ranges known at compile time.