Function-returned structures

tps at sdchem.UUCP tps at sdchem.UUCP
Mon Feb 9 15:54:09 AEST 1987


In article <4319 at brl-adm.ARPA> KLH at sri-nic.arpa (Ken Harrenstien) writes:
>Here's an illustration.  Given:
>	struct s { int x; int a[10]; };	/* The structure */
>	struct s f();			/* The function returning it */
>	int i, *ip;			/* Bit players */
>
>Then a "typical" example of
>	i = f().x;		/* Legal and makes sense. */
>is explicitly permitted.  What I haven't been able to figure out is whether
>something like
>	i = f().a[i];		/* Looks plausible, whether legal or not. */
>should also be permitted.  The wording of both ANSI and H&S implies that it
>is, and I can't find anything to do with lvalue-ness or array-to-pointer
>conversion that would prohibit it.  But if you accept this case, then you
>are allowed to create pointers to structures (or structure components)
>returned by such functions.  After all,
>	i = *(f().a + i);	/* is "precisely equivalent" to f().a[i] */
>	ip = f().a;		/* therefore f().a is a valid expression */
>				/* although it is pretty nonsensical */
>
>But the whole point of making the function result a non-lvalue is so
>you cannot refer to it in this way!  &(f().x) for example is illegal.
>There seems to be some inconsistency here, and I'm not sure how to
>resolve it.  I'm not so worried about the user screwing up (there are
>plenty of other ways to accomplish this) as I am about making sure my
>compiler has both a definite way of knowing whether a construct is
>legal, and a way of implementing it if it is.  (Incidentally, 4.3BSD C
>won't even accept f().x)
>Comments?

4.3BSD won't take

	f().x,
	
but amazingly it will take
	
	( &f() ) -> x

And if you try

	p =	&f();
	printf( "%d\n", *p );

it even more amazingly prints the "right" answer.
Perhaps if this is really too hard to check in a compiler
(is this what you are
saying?), ANSI should make the result of

	f().a

undefined and then leave checking of this to lint.








|| Tom Stockfisch, UCSD Chemistry	tps%chem at sdcsvax.UCSD



More information about the Comp.lang.c mailing list