Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning result to eax (IA-32 Assembly language)

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?

like image 542
ddriver1 Avatar asked May 05 '11 12:05

ddriver1


2 Answers

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.

like image 52
Jasper Bekkers Avatar answered Oct 22 '22 13:10

Jasper Bekkers


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).

like image 42
Pontus Gagge Avatar answered Oct 22 '22 13:10

Pontus Gagge