Takes advantage of the decrement instruction setting the zero-flag so no explicit test instructions are necessary.
This modified excerpt was taken from the test ROM that comes with the GameBoy bgb emulator. This example is a counter that repeats a specified number of times based on what is loaded into registers D and E (D being the High byte), but the countdown iterates in an interesting way. Rather than counting down the usual way (2000, 19FF, 19FE, ..., 0002, 0001, 0000), it iterates as (2000, 20FF, 20FE, ... 0102, 0101, 0000). The DEC instruction automatically tests for a zero result. By keeping the higher byte non-zero until the very end, the zero flag on the high byte is able to indicate the end of loop. This algorithm handles all of the zero testing implicitly without having to use additional test instructions.
There is a function call at the beginning of the routine. It simply increments the high byte if the lower byte is non-zero. This is just offsetting it so that the high-byte will be non-zero until the desired count is complete.
-------------------------------------------------------------------------------------------------- 0160 11 00 20 LD DE, 2000 // Load 0x2000 (count) into register DE . . 03B7 CD DD 03 CALL 03DD ...DO STUFF 03BB 1D DEC E // Decrement E 03BC 20 FC JR NZ, FC // Jump to 03BA if E not zero 03BE 15 DEC D // Decrement D 03BF 20 F9 JR NZ, F9 // Jump to 03BA if D not zero 03C1 C9 RET . . //*FUNCTION* Increments D(high byte) if E(low byte) not zero 03DD F5 PUSH AF 03DE 7B LD A, E 03DF B7 OR A // Set the Z flag if A == 0 03E0 28 01 JR Z, 01 // Jump to 03E3 (skip next instruction) if zero 03E2 14 INC D // Increment D 03E3 F1 POP AF 03E4 C9 RET --------------------------------------------------------------------------------------------------======