[comp.lang.c] Return of arrays and structures,...

gwyn@smoke.brl.mil (Doug Gwyn) (04/18/91)

In article <1991Apr17.173914.3683@milton.u.washington.edu> rburgess@milton.u.washington.edu (Rick Burgess) writes:
>Apparently values of structures can be returned from functions under the ANSI
>standard...?

Yes; this has been existing practice in UNIX C compilers since around 1978.

>Can Arrays also?

No.

>Aren't structures essentially a pointer constant just like arrays?

No, they never were interpreted as pointers, unlike array names in most
expression contexts.

>When you pass a structure and not a structure pointer aren't you gonna end up
>with the version modified in the routine it is passed to just like with
>arrays?

No, structure arguments and return value are passed "by value", just like
every other type in C.  To modify a structure in the caller one would have
to pass an explicit pointer to it.

>Can anyone give some logical or anectdotal suggestions on when pointers are
>well used, when structures and arrays themselves, and when it is actually
>good to return either or both of these rather than just letting them be
>modified directly by the subroutine?
>(I know, I should probably take a compsci course, right?)

No, but you SHOULD read a good C textbook (I recommend K&R 2nd Edition).

Prototypical examples of functions that return structs are:
	struct complex { double re, im; };
	extern struct complex c_add( struct complex a, struct complex b );
and
	typedef struct { short x, y; } point;
	typedef struct point vector;
	extern point p_add( point p, vector v );
For really large structures it is usually more efficient, albeit less
convenient, to use pointers.