Loop Control: Next & Exit Statements
The following are two additional statements that can be used to control the looping construct:
Next
The next
statement is used to skip the remaining code in the current iteration of the loop and proceed to the next iteration. In a for-loop, the index variable will be incremented or decremented automatically before the next iteration. In a while-loop, this behavior depends on the logic applied. There are two ways to use the next
statement.
next when (condition);
if (condition) then
next;
end if;
Exit
The exit
statement is used to forcibly stop the loop. When this statement is executed, the loop will terminate immediately, and the program will continue executing the code that follows the loop. There are two ways to use the exit
statement.
exit when (condition);
if (condition) then
exit;
end if;
Example
Below is an example of a for-loop that uses the next
and exit
statements.
process
variable i: integer := 0;
begin
for i in 0 to 7 loop
if i = 3 then
next; -- Skip the rest of the code in this iteration
elsif i = 5 then
exit; -- Exit the loop
end if;
reg(i) <= reg(i+1);
end loop;
end process;
This VHDL code snippet demonstrates the use of a for-loop within a process statement. Here's the detailed explanation:
-
Process Declaration:
- The process block is declared, and a variable
i
of type integer is initialized to 0.
- The process block is declared, and a variable
-
For-Loop:
- The for-loop iterates over the range from 0 to 7, inclusive. The loop variable
i
is automatically created and incremented with each iteration.
- The for-loop iterates over the range from 0 to 7, inclusive. The loop variable
-
Conditional Statements:
- Inside the loop, there are two conditional checks:
-
if i = 3 then
: Ifi
equals 3, thenext
statement is executed. This causes the loop to skip the remaining code in the current iteration and proceed to the next iteration. -
elsif i = 5 then
: Ifi
equals 5, theexit
statement is executed. This causes the loop to terminate immediately, and the process continues with the code following the loop.
-
- Inside the loop, there are two conditional checks:
-
Register Assignment:
- If neither of the above conditions is met, the code
reg(i) <= reg(i+1);
is executed. This assigns the value ofreg(i+1)
toreg(i)
.
- If neither of the above conditions is met, the code
-
End Loop and Process:
- The loop ends after completing the iterations from 0 to 7, unless exited early by the
exit
statement. - The process block ends after the loop.
- The loop ends after completing the iterations from 0 to 7, unless exited early by the
Summary
- The loop iterates from 0 to 7.
- When
i
is 3, the loop skips the current iteration. - When
i
is 5, the loop exits. - For other values of
i
,reg(i)
is assigned the value ofreg(i+1)
.