Function returning Structure: How does it work?

Howard Siegel siegel at stsci.EDU
Fri Jun 1 14:03:11 AEST 1990


Conrad Wong (cwong at cory.berkeley.edu) writes:
>The following seems to be an "easy" question.  However, after thinking
>about it, I find that I don't really understand how it really works...
>
>   [simple stuct declaration and function returing struct...]
>
>Now, it seems that the storage space for 'structure' has to be allocated
>on the heap (not on stack).  However, wouldn't this create a lot of
>garbages you won't be able to free?  For example:
>
>   [other stuff...]
>
>I don't think my assumption about garbage is correct.  However, I
>just can't think of how the C-compiler actually handles it.  Can 
>some one please disclaim/confirm what I have said.  Or even better,
>can some one please enlighten me to show me how this is really done.

I can not say that all C compilers work this way, but on VMS (any version)
this is the story.  (Note that this is (should) be the same for all
languages that adhere to DEC's Common Calling Convention which is
documented someplace in the umpteen feet of manuals).  At least for
the example in question, I have tried it out and looked at the machine
code created by the VAX C compiler.

For functions that return a simple (atomic?) data type, the returned
value is put into register 0 if it is 4 bytes or smaller or into the
register 0/1 pair if it is 5-8 bytes big.  If the value to be returned
is bigger than 8 bytes then the compiler shifts the argument list
over and creates a new first argument which is a pointer to an object of
the proper data type.

Thus, if the function in question is defined in the code as:

    STRUCT function(int number)

the compiler will create code as if the function were defined as:

    void function(STRUCT *structure, int number)

In the calling routine, the compiler creates a temporary variable for
the return value on the stack (not the heap) and uses that variable in
the actual function call argument list.

Again, this is just how it happens on VMS and with the VAX C (not quite
ANSI) compiler.  Your mileage with other OS's will vary, but I would
imagine they'll act similarly.

(Sorry I could not provide compiler listings with the machine code
in them, but the link to the VMS machine is flaky at the moment).
-- 
    Howard Siegel    (301) 338-4418
    TRW   c/o Space Telescope Science Institute   Baltimore, MD 21218
    ARPA:  siegel at stsci.edu          SPAN:  STOSC::SIEGEL
    uucp:  {arizona,decvax,hao}!noao!stsci!siegel



More information about the Comp.lang.c mailing list