push and pop in Assembly
The stack grows down; last in, first out swaps for free.
; The stack grows down; push and pop move rsp for you.
global _start
section .text
_start:
mov rax, 3
mov rbx, 39
push rax ; save 3
push rbx ; save 39
pop rax ; rax = 39 (last in, first out)
pop rbx ; rbx = 3
add rax, rbx ; 42, values swapped and summed
mov rdi, rax
mov rax, 60 ; exit code 42
syscall
How it works
pushwrites and moves rsp;popdoes the reverse.- Popping in the same order swaps the two values.
- rsp bookkeeping is entirely implicit here.
Keywords and builtins used here
addglobalmovpoppushraxrbxrdisectionsyscall
The run, in numbers
- Lines
- 17
- Characters to type
- 389
- Tokens
- 41
- Three-star pace
- 60 tpm
At the three-star pace of 60 tokens a minute, this run takes about 41 seconds.
Step 1 of 3 in The stack, step 19 of 31 in Language basics.