Values can be stored in three places:
- a register
- a memory address
- a port
When using the stack you are simply putting the value of a register pair in (push
), or loading the value of a register pair from (pop
), an address in memory pointed to by the stack pointer (sp
). Since the stack is just memory, the meaning of any value is arbitray, you will need to balance your pop
and push
to pop the value you intended - only you know what is actually on the stack.
An easier and less error prone approach - albeit slower - is to dedicate some memory to storing your value:
var.counter: defw 0
...
ld bc,2
ld (var.counter),bc
...
INIT:
ld bc,(var.counter)
cp 2
jp z, INIT2
Sometimes (if you are executing in RAM) limited self modifying code can be effective:
ld bc,2
ld (smc.counter+1),bc
...
INIT:
smc.counter:
ld bc,0
cp 2
jp z, INIT2
And as mentioned in the comments to your question cp
compares the value with the accumulator (register a
) and not register pair bc
.