A86: Re: If/then in asm?


[Prev][Next][Index][Thread]

A86: Re: If/then in asm?




This stuff just involves knowing your processor flags.  JR only supports
zero and carry, RET and JP support all.  While JP is faster and supports all
the flags, JR should be used if possible, since it takes 2 bytes instead of
3.  RET always takes 1 byte and can be used as a jump.

; if (num) == 5 then equal else not_equal

 ld a,(num)
 cp 5
 jr nz,not_equal
equal:
 ...
 jr next
not_equal:
 ...
next:

And the next question you're going to ask...

; unsigned numbers (0-255)

 ld a,(num)
 cp 5
 jr z,equal_to_5
 jr c,less_than_5
greater_than_5:

; signed numbers (-128 to 127)

 ld a,(num)
 cp 7
 jr z,equal_to
 jp m,less_than
greater_than:

Also...

; unsigned

 ld a,(num)
 cp 19
 jr nc,greater_than_or_equal_to
less_than:


; signed

 ld a,(num)
 cp 13
 jp p,greater_than_or_equal_to
less_than:

Using RET as a jump:

 ld hl,label
 push hl
 ...
 ret    ; same as <JP label>

This is useful when you have a switch/case-type structure where all of the
sections jump to the same ending label.  Snce RET is only one byte, it can
save a lot of space:

 ld hl,done
 push hl
 ld a,(num)
 cp 5
 jr label1
 cp 19
 jr label2
 cp 31
 jr label3
 ...
label1:
 ...
 ret       ; JP done  (1 byte!)
label2:
 ...
 ret
label3:
 ...
 ret
 ...
done:

> How would I setup an if...then... statement in asm?
>
> Thanks,
> Ben
>
>



References: