I need to make a function that swaps two variables by reference (Transferring the values should be on stack, not through registers), when i try to check if the values swapped I have an error (on emu8086): (11) wrong parameters: CMP [ax], [bx] (11) probably it's an undefined var: [ax]
org 100h
include print.inc ;printing library
start:
x db 0x7Fh
y db 0x80h
lea ax, x ;get address
lea bx, y ;get address
push ax
push bx
call swap
cmp [ax], [bx]
jl label1;check if values swapped
jmp end2
label1:
PRINTN "values swapped" ;print if the values swapped
end2:
mov ah, 0
int 16h
ret
proc swap ;swap function
push bp
mov bp, sp
mov cx, [bp 4]
xchg cx, [bp 6]
mov [bp 4], cx
jmp end1
end1:
pop bp
ret
endp swap
CodePudding user response:
I'm guessing you're trying to implement the classic C swap:
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
So I'll break down what needs to be done step-by-step. Firstly, you have your data defined after your start
label and then code right after. Unless there's additional hardware abstraction going on here, the CPU will interpret the 0x7F
and 0x80
as CPU instructions, doing who knows what. So move your declared data to a different section.
proc swap ;swap function
push bp
mov bp, sp
;sp 0 = bp
;sp 2 = ret
;sp 4 = pushed bx
;sp 6 = pushed ax
I like to have comments like these to remind myself which variable is which, since things get confusing very quickly.
Now, you have to remember that since you used LEA
to populate ax
and bx
, what you have in those registers are pointers to memory. So ax
does not equal 0x007F
, but rather the address where that 0x007F
is stored. So you'll need to dereference the arguments after loading them off the stack.
proc swap ;swap function
push bp
mov bp, sp
;sp 0 = bp
;sp 2 = ret
;sp 4 = pushed bx
;sp 6 = pushed ax
mov di,[bp 4] ;loads &y into di
mov si,[bp 6] ;loads &x into si
mov ax,[di] ;loads 0x0080 into ax
mov cx,[si] ;loads 0x007F into cx
;now swap the values at those addresses
mov [si],ax ;*a = 0x0080
mov [di],cx ;*b = 0x007F
pop bp
ret
endp swap