Reputation: 27
Below is a piece of code that is supposed to store a digit (or multiple) into a stack. R6 is the stack pointer. Other than that, I don't quite understand whats happening. Why would you store R6 in R1, then clear it? (I believe AND R1,R1,0 clears R1) New to LC3, so just looking for clarification. Thank you in advanced!
; storing in the stack
STR R1, R6, 0 ;store num in first space
AND R1, R1, 0
STR R3, R6, 1 ; store operator in 2nd place
ADD R6, R6, 3 ; increment the stack
STR R6, R6, -1 ; and provide a link to it in slot 3
JSR INPUT ; back to input
Upvotes: 1
Views: 2113
Reputation: 647
I can't say I entirely understand, what's going on, but just to put some different comments down:
STR R1, R6, 0 ; MEM[R6] <- R1
AND R1, R1, 0 ; R1 <- 0
STR R3, R6, 1 ; MEM[R6+1] <- R3
ADD R6, R6, 3 ; R6 <- R6 + 3
STR R6, R6, -1 ; MEM[R6-1] <- R6
This means that your memory now looks like:
0: original contents of R1
1: original contents of R3
2: address of memory slot 3
3: empty, now pointed to by R6
So really, this code is creating a singly-linked list with two values stored in each node. It's a little weird, since it's being constructed in a way that relies explicitly on the sequential nature of the memory, which therefore would work just fine with an array and does not need a linked list.
One thing to keep in mind is that what makes a stack a stack is the operations it runs (i.e. push and pop) as much as the structure itself. Here's perhaps a simpler stack example
LEA R1, STACK ; R1 is the next empty location
PUSH: ; Takes new value in R0
ADD R1, R1, 1 ; Increment pointer
STR R0, R1, 1 ; MEM[R1+1]<-R0
RET
PULL: ; Returns new value in R0
LDR R0, R1, -1 ; R0<-MEM[R1-1]
ADD R1, R1, -1 ; Decrement pointer
RET
This does no bounds checking, so it will happily run all over unallocated memory.
Upvotes: 1