Not only that, but...

Mike Don't have strength to leave Meyer mwm at eris.BERKELEY.EDU
Wed Nov 12 07:04:56 AEST 1986


In article <166 at houligan.UUCP> dave at murphy.UUCP (H. Munster) writes:
>In article <630 at dg_rtp.UUCP>, throopw at dg_rtp.UUCP (Wayne Throop) types:
>>Again folks, play it safe: *NEVER* have two side-effects on a single
>>object in a single expression.
>
>Not only that, but: don't even *USE* an assigned-to object anywhere else
>in the expression!

The first isn't quite sufficient, as Dave showed. But the second is an
over-reaction.  There are operators in C that are guaranteed to
preserve order, so you can make an assignment then use the variable
assigned to.

To wit, '||' and '&&' WILL be evaluated left-to-right (and short
circuit), so you can safely write:

	while ((c = getchar()) != TERMINATOR && c != EOF)
		;

Since leaving off the test for EOF is usually a bug, this is a
good thing. I know, this example can be rewritten as a do-while, and
you can move subsequent tests to the top of the loop with breaks. But
the first case isn't always true, and the second isn't as readable as
the above C idiom.

	<mike



More information about the Comp.lang.c mailing list