short circuit evaluation

jas at rtech.UUCP jas at rtech.UUCP
Wed Feb 4 04:10:38 AEST 1987


Apropos of whether it is legitimate to short-circuit an expression
evaluation, when a short-circuited operand has side effects, Henry
Spencer writes:
> Yeah, some variants of the V7 pdp11 C compiler did, in cases where one of
> the operands was a compile-time constant known to be 0....
> Never bothered me, since I view side effects
> inside expressions as being unjustifiable pornography except for some very
> specific cases.  I did ask Dennis about it....  His reply ... was
> roughly "I think it is defensible in principle, but it caused so many
> complaints that newer versions of the compiler don't do it".

I don't know, Henry, I think you and Dennis are on thin ice here.  In
Pascal, you're right; but C is close to being a pure expression
language, in which the only way to change machine state is by a side
effect.  Three examples:  (1) An assignment is an expression; as a side
effect, it stores the value of its right operand in the memory location
represented by the left operand.  (2) The comma is a binary operator whose
semantics are:  evaluate the left operand, discard the result, then
evaluate the right operand, whose value is the value of the whole
expression.  Obviously, this is only useful if the left operand has
side effects.  If a short-circuiting compiler decides never to evaluate
the left operand, because it will not affect the value of the whole
expression, then the comma operator becomes meaningless.  (3) The
most common form of statement in C is (syntactically), "<stmt> ::=
<expression> ';'".  The semantics associated with this production are,
"evaluate the expression and discard the result."  If a compiler
writer were to decide to short-circuit the evaluation, since the result
is being discarded, s/he would end up with a pretty useless compiler.

Now, one might say, "It is poor style for an expression with side
effects to itself be an operand of an expression other than a "comma"
expression."  (Though this prohibits the ever-popular "if ((c = getchar())
!= EOF)".)  But though this may be a valid stylistic constraint, I
would hate to see it embedded in the semantics of the language.
-- 
Jim Shankland
 ..!ihnp4!cpsc6a!\
                  rtech!jas
..!ucbvax!mtxinu!/



More information about the Comp.lang.c mailing list