For versus Do/While versus While
In the examples you've seen so far of $Order loops, we've used an argumentless For construct, as opposed to Do/While or While constructs. For used in this way has some advantages over the other constructs. If you wish, review argumentless For, and use your browser's Back button to return here to learn more.
The advantage argumentless For has occurs in cases where the condition that terminates the loop is within the repeating code, rather than at the beginning (While) or the end (Do/While). For allows for the condition to be checked only once. The other constructs check the condition twice. See the code samples below for an illustration.
compareloop ; different styles of looping
/* the first three loops are logically equivalent,
but the 1st is recommended over the 2nd and 3rd versions.
the 4th loop is a copy of the third loop,
but without the internal quit, so there's a logical error. */
usefor write !, "Using For"
for
{
set x = $random(10)
quit:(x = 5) // this quit ends the code block AND terminates the loop
write !, x
}
usewhile write !!, "Using While"
set x = ""
while x '= 5 // this condition is evaluated each time, for no reason
{
set x = $random(10)
quit:(x = 5) // this quit ends the code block AND terminates the loop
write !, x
}
usedo write !!, "Using Do/While"
do
{
set x = $random(10)
quit:(x = 5) // this quit ends the code block AND terminates the loop
write !, x
}
while x '= 5 // this condition is evaluated each time, for no reason
badusedo write !!, "Using Do/While, but it writes the terminating 5"
do
{
set x = $random(10)
write !, x
}
while x '= 5 // this condition terminates the loop (a little too late)