Address of a variable: Difference between revisions

Line 1,954:
> *baz
5</pre>
 
=={{header|Z80 Assembly}}==
A variable's address is known in advance if the programmer is writing the assembly code themselves. In order to load from a variable, the address must be specified as an operand. So "getting the address" doesn't really apply to Z80 Assembly.
 
Setting an address is just storing a register into memory. There are several ways to do this:
===Specifying a Memory Location===
Only the accumulator <code>A</code> can do this.
<lang z80>foo equ &C000
ld (foo),a</lang>
 
===Using BC or DE===
Only the accumulator <code>A</code> can do this.
<lang z80>foo equ &C000
bar equ &C001
 
ld bc,foo ;notice the lack of parentheses here. This is important.
ld (bc),a
 
ld de,bar
ld (de),a</lang>
 
===Using HL===
The 8-bit registers <code>A,B,C,D,E</code> can all do this. H and L cannot, unless the value being stored happens to equal that "half" of the memory location.
<lang z80>foo equ &C000
bar equ &C001
ld hl,foo
ld (hl),b ;store the contents of B into foo
 
;since bar just happens to equal foo+1, we can do this:
 
inc hl
ld (hl),c ;store the contents of C into bar</lang>
 
===16-Bit Values into A Specified Memory Location===
Storing a 16-Bit value is a little more complicated. The registers <code>BC,DE,HL,IX,IY,SP</code> can all do this, with a specified memory location. The "low byte" of the register (<code>C, E, L, IXL, IYL,</code> and the low byte of <code>SP</code>) are stored at the memory location specified in parentheses, and the "high byte" of the register (<code>B, D, H, IXH, IYH,</code> and the high byte of <code>SP</code>) are stored in the memory location <i>after that</i>. The Game Boy/Sharp LR35902 can only do this with SP, and no other registers.
 
<lang z80>foo equ &C000
bar equ &C001
 
ld (foo),bc ;store C into "foo" and B into "bar"</lang>
 
Beware! In this example, the second instruction clobbers part of the first. It's important to be careful when storing 16-bit values into memory.
<lang z80>foo equ &C000
bar equ &C001
 
ld (foo),de ;store E into &C000 and D into &C001
ld (bar),bc ;store C into &C001 and B into &C002</lang>
 
{{omit from|8th|Impossible to access address of a variable}}
1,489

edits