Assembly Language for Beginners

(nextflipdebug2) #1

1.11. MORE ABOUT RESULTS RETURNING


1.11.3 Returning a structure.


Let’s go back to the fact that the return value is left in theEAXregister.


ThatiswhyoldCcompilerscannotcreatefunctionscapableofreturningsomethingthatdoesnotfitinone
register (usuallyint), but if one needs it, one have to return information via pointers passed as function’s
arguments.


So, usually, if a function needs to return several values, it returns only one, and all the rest—via pointers.


Now it has become possible to return, let’s say, an entire structure, but that is still not very popular. If
a function has to return a large structure, thecallermust allocate it and pass a pointer to it via the first
argument, transparently for the programmer. That is almost the same as to pass a pointer in the first
argument manually, but the compiler hides it.


Small example:


struct s
{
int a;
int b;
int c;
};


struct s get_some_values (int a)
{
struct s rt;


rt.a=a+1;
rt.b=a+2;
rt.c=a+3;

return rt;
};


...what we got (MSVC 2010/Ox):


$T3853 = 8 ; size = 4
_a$ = 12 ; size = 4
?get_some_values@@YA?AUs@@H@Z PROC ; get_some_values
mov ecx, DWORD PTR _a$[esp-4]
mov eax, DWORD PTR $T3853[esp-4]
lea edx, DWORD PTR [ecx+1]
mov DWORD PTR [eax], edx
lea edx, DWORD PTR [ecx+2]
add ecx, 3
mov DWORD PTR [eax+4], edx
mov DWORD PTR [eax+8], ecx
ret 0
?get_some_values@@YA?AUs@@H@Z ENDP ; get_some_values


The macro name for internal passing of pointer to a structure here is$T3853.


This example can be rewritten using the C99 language extensions:


struct s
{
int a;
int b;
int c;
};


struct s get_some_values (int a)
{
return (struct s){.a=a+1, .b=a+2, .c=a+3};
};


Listing 1.98: GCC 4.8.1

_get_some_values proc near

Free download pdf