short circuit evaluation

hoey at nrl-aic.arpa hoey at nrl-aic.arpa
Thu Feb 12 07:48:19 AEST 1987


    From: Chris Torek <mimsy!chris>
    Message-Id: <5199 at mimsy.UUCP>
    Date: 26 Jan 87 02:17:54 GMT

    ...
	    c = *p++ & *q++;
	    /* are both p and q always incremented? */

    I can find no promise in K&R that bitwise expressions are not short
    circuited even in the presence of side effects.  The ANSI draft
    may have more to say.  In any case, I would advise not counting on
    full evaluation.

K&R's note that ``The order in which side-effects take place is ...
unspecified'' conspicuously fails to lend credence to this point of
view.  Why should they unspecify the order, and not unspecify whether
side-effects take place at all?  It seems to me that the idea of
bitwise operators (or other operators lacking sequence breaks) not
performing all their side-effects is so counterintuitive that it should
be outlawed.  At the very least, a prominent warning must be included
in the standard.  Since this is a contentious issue, a standard silent
on the point is no standard.

If compilers are allowed to fail to increment both p and q, I would
assume that they are also allowed to short-circuit evaluation of *, /,
%, <<, >>, >=, and <= when the result is known by evaluation of one
argument.  This may also occur in evaluation of <, >, ==, and != when
one of the arguments is being promoted from a restricted range.  Shall
we perhaps leave unspecified whether

	*p++ = 0;

increments p when the compiler can deduce that *p is already 0?

      It is even conceivable that a compiler might generate

	    if ((c = *p) != 0)
		    c &= *q;
	    p++;
	    q++;

    which, if p and q point to device registers, is not the same!

I find this perfectly acceptable, due to the above quote from K&R.  If
you are accessing device registers code in C, you are expected to know
what the compiler is going to do with your code.  If you have an
optimizing compiler, you also have to worry about dead variables and
code movement for code in which pointer dereference can cause
side-effects.

    From: Henry Spencer <utzoo!henry>
    Message-Id: <7588 at utzoo.UUCP>
    Date: 30 Jan 87 22:08:26 GMT

    ...  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 at one point, since strict reading of K&R
    suggested it was a bug.  His reply, as I recall it, 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".

Are your cases of justifiable pornography sufficiently specific that
they should appear in the standard?  I believe the standard must be
precise here, and the ``so many complaints'' lead me to believe that
the answer must be in favor of guaranteed execution of side-effects.

Dan Hoey



More information about the Comp.lang.c mailing list