Function returning Structure: How does it work?

Stephen Clamage steve at taumet.COM
Fri Jun 1 01:43:08 AEST 1990


In article <8048 at crdgw1.crd.ge.com> larocque at jupiter.crd.ge.com (David M. LaRocque) writes:
>One instance I thought of that one may want to use a function that
>returns a structure is as an alternative to malloc.
>
>struct point { int x; int y; };
>struct point makepoint(int x, int y);
>struct rect { struct point pt1; struct point pt2; };
>struct rect screen;
>screen.pt1 = makepoint(0, 0);

In this example, the return from makepoint() is copied to a static
(in this case global) variable.  Following the call to makepoint, what
it actually returned is irrelevant, since it can no longer be referenced.
The copy stays where it is (in this case, globally available until the
end of the program).

If you had a local struct assigned the return from makepoint(), that
local struct would contain the value until it's containing function
returned, at which time it would disappear.

Think about a function returning an int.  Where is the int located?  Can
it be clobbered later?  Any function return value must be used (copied)
immediately as part of the expression calling the function.  This is as
true for structs as for ints.
-- 

Steve Clamage, TauMetric Corp, steve at taumet.com



More information about the Comp.lang.c mailing list