cond. op. on ='s LHS

Stephen Carlson scc at rlgvax.Reston.ICL.COM
Fri Feb 15 05:09:25 AEST 1991


In article <4155 at cernvax.cern.ch> burow at cernvax.cern.ch (burkhard burow) writes:
>I'm wondering if anyone has any comments on using:
>
>       *(a==b?&c:&d) = 1;
>instead of:
>       if (a==b) c=1;
>       else      d=1;
>

The GNU C compiler as an extension to the C programming language allows the
result of the ternary operator to be an lvalue:

	((a == b) ? c : d) = 1;

Normal C, however, requires that the result of the ternary operator be an
rvalue, hence the subterfuge with the & and * operators (the result of a
* operator is an lvalue).

My only remark is that this may be preferable in the case where the right
hand of side of the expression is some long expression, like:

	*(a==b?&c:&d) = some_long_and_hairy_expression;

Since it written only once and not twice, there is less chance for errors
due to inconsistencies, as in:

	if (a == b) c = some_long_and_hairy_expression;
	else        d = some_lomg_and_hairy_expression;

Here, those two long expressions are not the same and it is not clear to the
maintainer whether they should be the same.  To paraphrase Aristotle, same
things should be the same; different things different.  The same argument is
the basis for the += type of operators:

	some_long_and_hairy_lvalue += 2;

is better than:

	some_long_and_hairy_lvalue = some_long_and_hairy_lvalue + 2;


Of course, since this subterfuge is especially convultuted and hairy, I
would reccommend:

	e = some_long_and_hairy_expression;
	if (a == b)
		c = e;
	else
		d = e;

Here, it is clear that either c or d are to be assigned to the same
expression in either case.  A good compiler will put the value in a
temporary anyway.

-- 
Stephen Carlson            | ICL OFFICEPOWER Center
scc at rlgvax.opcr.icl.com    | 11490 Commerce Park Drive
..!uunet!rlgvax!scc        | Reston, VA  22091



More information about the Comp.lang.c mailing list