[comp.lang.c] Structure references

chris@mimsy.UUCP (Chris Torek) (07/08/87)

>>Should I define
>>	vector center;
>>	center = s2->o;
>>if I plan to use s2->o several times?  Thanks for any help.

In article <220@wrs.UUCP> dg@wrs.UUCP (David Goodenough) writes:
>You'd do better with
>	vector *center;
>	center = &(s2->o);
>and refer via center->.

Not necessarily.  In particular, on familiar register-offset-address
machines, both `center->z' and `s2->o.z' produce the same code,
save that the offset is different.  (Zero offsets are sometimes
more efficient than nonzero offsets, so center->x *may* be faster
than s2->o.x.  The difference is probably unnoticeable.)

>whenever you do a structure reference e.g.
>	foo.bar
>the compiler internally has to convert it to
>	(&foo)->bar

This is quite false; indeed, it may be exactly backwards in some
compilers.  `foo->bar' can always be converted to `(*foo).bar',
but in particular, given

	struct foo { int i; } f();
	int i = f().i;	/* legal in dpANS C anyway */
	/* but note that	int *ip = &f().i;
	   is dangerous: `do not try this at home'. */

there is no address for the return value of function f.  Some
compilers create one internally, and others just wing it (the
structure fits in a register).  And of course still others get it
wrong entirely (4.3BSD PCC, e.g.).

>... NOTE also that these two will have very different results if
>you start assigning back into center....

Note it well!  It is quite easy to break code while `tuning' it.
The Valar know I have done it often enough myself.

Incidentally, while comp.lang.c is drowning in a sea of style strife,
let me further the foam:

>	center = &(s2->o);

The parentheses are unnecessary, and look quite odd to me.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7690)
Domain:	chris@mimsy.umd.edu	Path:	seismo!mimsy!chris