Null object: Difference between revisions

m
Line 28:
[1]
</pre>
 
=={{header|6502 Assembly}}==
{{trans|Z80 Assembly}}
 
Technically there is no such thing as a null pointer; all pointers point to ''something.'' It's a matter of what you're willing to give up. Often the null pointer is thought of as memory address 0, and on many CPUs this is the case - however this is most assuredly '''not''' the case on the 6502. Reason being, zero page RAM is limited and quite valuable, given that there are only 256 bytes of it and it is much more efficient to access than regular memory. As such, declaring <code>$0000</code> to be the null pointer would be a very poor choice. Ideally, the null pointer on a 6502 should:
* Be somewhere that isn't zero page RAM
* Be somewhere that we cannot change at runtime (e.g. read-only memory) or doing so would cause major problems (the vector table)
* Point to something that has no value to the programmer.
 
We can choose quite a few places, the easiest one I can think of is <code>$FFFF</code>. Although it sort of breaks our first rule, as when dereferenced as a 16-bit value, you get the value stored at <code>$0000</code> as the high byte, we still can access <code>$0000</code> normally anyway. Since it points to the high byte of the interrupt request vector, it's something we don't want to (or most likely can't) modify at runtime, and is of no use to us (if we really wanted the IRQ handler's address we'd dereference <code>$FFFE</code> instead.
 
How a null pointer is implemented is very simple. You decide beforehand what your null pointer will be, and before you dereference a pointer variable, compare it to the null pointer, and if they're equal, don't dereference it. That's all there is to it.
 
<lang 6502asm>lda pointer ;a zero-page address that holds the low byte of a pointer variable.
CMP #$FF
BNE .continue
lda pointer+1
CMP #$FF
BNE .continue
RTS ;return without doing anything
.continue</lang>
 
=={{header|8th}}==
1,489

edits