[A83] Re: jr $ + hl


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

[A83] Re: jr $ + hl




First, get it out of your head that $ is anything magical.  It is not.  You
don't need an assembler to write code.  You could do it all by hand with
opcodes.  It would just be very annoying and tedious.  And, yes, people used
to have to program this way.

The assembler calculates addresses for you, so that you can change code
around, and not have to recalculate everything by hand.  You should be
familiar with how a label works:

.org $8000

 nop
Foo:
 ...

 jp Foo

The "nop" instruction will be at address $8000, because org tells the
assembler to start at $8000.  It is one byte long, so the label "Foo" will
have a value of $8001.  On the second pass, the assembler will replace "Foo"
with $8001, giving the instruction "jp $8001".  You know that you can also
do expressions:

 jp Foo+2

This will give the instruction "jp $8003".  $ merely means the address at
the start of the instruction:

.org $8000

 jp $+3

Would be the same as:

.org $8000

 jp Foo
Foo:

Because "jp" is a three byte instruction, they both jump to $8003.

So, what you are wanting to do is something like the following:

Foo:
 jr Foo+hl

Obviously, this is impossible, as the z80 doesn't have indexing modes like
that.  So, you need multiple instructions.  Because a relative jump is one
byte, you don't need HL, as that is two bytes.  So, you have two choices. 
Do an absolute jump, or self modify the code to do a relative jump.  Because
you are using $, I assume that you are not needing position independent
code, so we will go with the simple method:

 ld de,$+3    ; load address at end of this instruction
 add hl,de    ; calculate complete address
 jp (hl)      ; jump to the value in HL

Now, I have always thought that opcode was confusing, so let me explain. 
Everywhere else you have paranthesis, it represents indirection.  There is
no real indirection taking place here.  This would be more easily written as
"jp hl", but that's not how it's written, so just pretend.  It does not load
the value from the address pointed to by HL, and then jump to that.

> is there anyway to tell the program to 'jr $+ hl'? or anything to that
> degree? thanks




References: