conditional expression evaluation question

DZ-015 @ Information Retrieval tiemann at mcc-pp.UUCP
Wed Jan 14 02:58:43 AEST 1987


In article <207 at rebel.UUCP>, george at rebel.UUCP (George M. Sipe) writes:
> I need to check a string, composed of byte triples, for a null area no
> less than MINSKIP triples in length.  A pointer, cp, is initialized to
> a triplet boundary.  After the test, it must remain on a triplet
> boundary.  Initially, I wrote the following:
> 
> 	while (cp < end && triples < MINSKIP)
> 		if ((*cp++ | *cp++ | *cp++) == 0) ++triples;
> 		else triples = 0;
> 
> After looking at it, I wasn't absolutely sure that it would perform as
> expected.  My question is "Does C guarantee execution of portions of a
> conditional expression, even when the result is known after partial
> evaluation?".  In my example, if the first byte is non-null, then the
> result is known to be false and there is no need to evaluate the
> remaining subexpressions.  However, I am counting on the whole
> expression being evaluated.  Assuming that C does guarantee full
> execution of the conditional test, would I be taking a significant
> chance that an optimizing compiler might be too tricky and
> (incorrectly) fail to do the full evaluation?
> 
> For now, I am using the following ugly code:
> 
> 	while (cp < end && triples < MINSKIP) {
> 		if ((*cp | *(cp+1) | *(cp+2)) == 0) ++triples;
> 		else triples = 0;
> 		cp += 3;
> 	}

I wouldn't have answered, but there was a wrong answer to the net, so
I thought I'd balance it out.

First of all, the bit-wise OR operator is not the same thing as the
logical disjuntion operator. The former does evaluate all its
arguments (though it may permute them as it sees fit (just like
+ or *)), while the latter does not. The answer to your question is
"No, C does not execute portions of a conditional expression which
are not needed", but you have not specified a conditional expression,
rather a logical one, which will be fully executed.

Michael Tiemann
tiemann at mcc.com



More information about the Comp.lang.c mailing list