Do-While Loops
Do-While loops are designed to do something until a certain condition evaluates to false
, but at least execute the action once. This means, that a do-while loop could also run infinitely when the condition never gets fulfilled.
Like the if statement, the condition of the do-while
loop must evaluate to a boolean value, but can hold complex, nested expressions.
Usage¶
Here is an example of a simple do-while
loop:
Spice | |
---|---|
Optional parentheses
As with the if statement, for loop and foreach loop, the parentheses around the head of the do-while
loop are optional.
If you wanted to intentionally achieve an endless loop, you would write something like this:
Usage of loop alternatives
If you somehow know how many times you want to execute something, we recommend you to use a for loop instead. If you want to iterate over a container of items, consider using the foreach loop.