9.3 'loop', 'LOOPNZ', 'loopnz' loops
-------------------------------------
Loops repeat a block of code until a specific variable or register
which acts as a loop counter has a value different from zero. After
execution of the block of code which contains the body of the loop, this
variable or register is reduced by 1 and then checked for whether it equals
zero. If the variable or register is not equal to zero, the loop body is
executed again and the process repeats.
An example of a loop with a variable used as a counter:
count = 5;
loop( count )
{WRITEWORD(count);
WRITELN();
}
Register CX is most effective for loops with a small body since in this
case the compiler generates a loop using the machine command 'LOOP'.
If the loop counter starts off at zero, the commands of the loop body
will be executed the maximum number of times for the variable range (256
times for an 8-bit counter with variable type byte or char, 65,536 times
for a 16-bit counter with variable type 'word' or 'int', and 4,294,967,296
times for a 32-bit counter with variable type 'dword' or 'dlong'.)
The following example executes a loop 256 times:
BH = 0;
loop (BH)
{
}
If the command specifies no loop counter, the loop will run forever.
The following example continuously outputs * to the screen:
loop()
WRITE('*');
The programmer may use or change the value of the loop counter variable
without a loop.
For instance, this loop is executed only three times:
CX = 1000;
loop( CX )
{
IF( CX > 3 )
CX = 3;
}
The operator can also abort a loop with 'BREAK' or 'break', as shown in
the following example:
CX = 1000;
loop( CX )
{
IF( CX > 3 )
BREAK;
}
In contrast to 'loop', in 'LOOPNZ' and 'loopnz' the loop argument is
checked for equality with zero before starting a loop. If the argument
equals zero, this loop body is not executed immediately (in this case the
loop body is executed the maximum number of times in the loop 'loop'). In
'LOOPNZ' it is most efficient when optimizing for code size if register
CX/ECX is used as the counter parameter. In this case the compiler will use
assembler instructions 'JCXZ/JECXZ' and 'LOOP'.