short circuit evaluation

tps at sdchem.UUCP tps at sdchem.UUCP
Mon Jan 26 06:58:46 AEST 1987


In article <5178 at mimsy.UUCP> chris at mimsy.UUCP (Chris Torek) writes:
>...
>    [For these, read `all zeroes bit pattern' for `OFF', and `all ones
>     bit pattern' for `ON'.  This is a text compression device.]
>
>      Given:	Possible methods of evalution:
>      ------	------------------------------
>	&	1.  Left side evaluated.  If OFF, evaluation stops;
>		    result is OFF.  If not, right side evaluated,
>		    and both results ANDed.
>		2.  Left side evaluated.  Right side evaluated.
>		    Results ANDed.
>		3.  Right side evaluated.  If OFF, evaluation stops;
>		    result is OFF.  If not, left side evaluated, and
>		    both results ANDed.
>
>	|	1.  Left side evaluated.  If ON, evaluation stops;
>		    result is ON.  If not, right side evaluated,
>		    and both results ORed.
>		2.  Left side evaluated.  Right side evaluated.
>		    Results ORed.
>		3.  Right side evaluated.  If ON, evaluation stops;
>		    result is ON.  If not, left side evaluated, and
>		    both results ORed.
>In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7690)

I don't think so.  "&" and "|" are like "+" and "-" in that you are not
guaranteed that the left side will be evaluated before the right.  Read
K&R sections 7.8-10, p. 190:
	"The [&|^] operator is associative and expressions involving [&|^]
	may be rearranged." 
Otherwise, how could an optimizing compiler change

	(a | b)  &  (b | c)

to

	(a & c) | b

or fold constants together as in changing

	(a | CONST1) & (a | CONST2)

to

	a | CONST3

where CONST3 is (CONST1 & CONST2).
	
I agree with you that the evaluation might be short circuited if the result
is already known.  However, I don't think this is guaranteed,
it might happen in the reverse order (right operand evaluated,
left operand skipped),
and it is guaranteed not to happen if the to-be-skipped operand has a
side effect.

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



More information about the Comp.lang.c mailing list