Skip to main content

Loop Control - Next & Exit

Loop Control - Next & Exit

The two control statements, next and exit, allow you to skip an iteration or terminate the loop entirely, giving you more precise control over your sequential code.

These statements can be used in both for and while loops.


One, The next Statement

The next statement immediately stops the current loop iteration and jumps to the beginning of the next one. Any code that comes after the next statement within the loop body is skipped for that specific iteration (same thing as in C!).

The syntax can be written in two ways:

-- Form 1: Using an if-statement
if <condition> then
    next;
end if;

-- Form 2: Using the 'when' keyword
next when <condition>;

Example: Summing Only Odd Numbers

To skip even numbers, the next statement is perfect!

-- Inside a process...
variable sum : integer := 0;
...
SUM_ODD_LOOP: for i in 1 to 10 loop
    -- If the number is even, skip to the next iteration
    next when (i mod 2 = 0);

    -- This line is only reached for odd numbers
    sum := sum + i;
end loop SUM_ODD_LOOP;
-- At the end, sum will be 1+3+5+7+9 = 25

Two, The exit Statement

The exit statement terminates the loop entirely. As soon as exit is executed, the program moves to the line after end loop.

The syntax is similar to next:

-- Form 1: Using an if-statement
if <condition> then
    exit;
end if;

-- Form 2: Using the 'when' keyword
exit when <condition>;
Example: Finding a Value in Memory

Say, we want to search through a memory to find an address that holds a specific value. Once we find it, there is no reason to continue searching.

-- Inside a process...
constant SEARCH_VALUE : std_logic_vector(7 downto 0) := x"A5";
variable found_addr : integer := -1; -- Default value
...
SEARCH_MEM_LOOP: for i in ram'range loop
    -- If the value at the current address matches,
    -- store the address and exit the loop immediately.
    if ram(i) = SEARCH_VALUE then
        found_addr := i;
        exit SEARCH_MEM_LOOP;
    end if;
end loop SEARCH_MEM_LOOP;

-- The code goes on...

Using exit makes the search efficient. It prevents the loop from doing unnecessary work after the item has been found.