I'm slightly confused as to how to return a value from a method in assembly language. As far as I know, the eax register is used to hold the result that is to be returned.
As an example, say my result is 4 and I use:
mov eax, 4
I now have 4 in eax and I want to return this method. Is there anything I need to do or will the instruction ret
automatically return the result?
The thing is that I don't know what's so special about register eax
since when I use ret
I go back to the caller, and the caller is free to access any of the registers I stored the result to, so why I couldn't just have used ebx
or ecx
with the result stored instead?
The reason the result is stored in eax
is convention; you can decide to store it in whatever register you like. However, the caller of your function is likely to assume that the content of the return value is stored in eax
. This also implies that you don't have to do any extra work when calling ret
.
What you are describing is a convention used by at least the Microsoft compilers. There's nothing particular about eax
in itself. If your assembly language function is called by C/C++ code compiled with one of the normal calling conventions, it will expect the result to be passed in eax
.
ret
merely returns control to the point where your function was called. No registers are affected (except for ESP
and the instruction pointer, of course).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With