Function returning Structure: How does it work?

Paul John Falstad pfalstad at phoenix.Princeton.EDU
Tue May 29 13:41:54 AEST 1990


In article <1990May28.215331.29333 at agate.berkeley.edu> m100-2ai at WEB.berkeley.edu () writes:
>in ANSI C, I can define a function returning STRUCT, such as the following:
>
>STRUCT function(void)
>{
>	STRUCT structure;
>
>	structure.num = 0;
>	/* Set other fields as well */
>	return structure;	
>}
>
>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

No, that's not how it's done.  I thought it was handled by having the
whole structure pushed on the stack, but it turns out that's not how its
done either.

I tried this program with Amiga Manx 5.0a:

struct foo { int a,b; };
struct foo fooer(void)  { struct foo bar = {1,2}; return bar; }
main()
{
struct foo bar;

  bar = fooer();
}

Manx compiled it the same way as the following:

struct foo fooer(struct foo *ptr)
{
struct foo bar = {1,2};

 *ptr = bar;
 return ptr;
}
main()
{
struct foo bar;

  fooer(&bar);
}

So that's one way to do it.  I tried this gcc on a VAX, and it handled it by
returning the structure in r0 and r1.  I made the structure much bigger
(too big to fit in registers), and gcc compiled it pretty much the same
way as above.

-- 
Paul Falstad  PLINK:Hypnos GEnie:P.FALSTAD net:pfalstad at phoenix.princeton.edu
Disclaimer: My opinions, which belong to me and which I own, are mine.
-Anne Elk (not AN elk!)  The sun never set on the British empire because
the British empire was in the East and the sun sets in the West.



More information about the Comp.lang.c mailing list