conditional expression evaluation question

J. Wong wong at rtech.UUCP
Fri Jan 16 09:23:41 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;
>
> ... [problems with above] ...
>
>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;
>	}
This is indicative of a problem with C:  It allows you to 
shoot yourself in the foot, by letting you be overly clever.

The problem here is that the programmer is using the ++ operator
for its side-effect and the | operator to guarantee that 'cp' is
incremented by three after the test.  That is, he's trying to be
clever and use side-effects, probably because he thinks its more
efficient.  His resolution is no uglier than his first solution in 
that neither is very clear (although the second is closer to what
he wants) or necessarily more efficient.

The `real' solution is this:

	while (cp < end && triples < MINSKIP)
	{
		if (cp[0] == '\0' && cp[1] == '\0' && cp[2] == '\0')
			++triples;
		else
			triples = 0;
		cp += 3;
	}

This is clear and to the point, and if you think about, 
not even significantly less efficient (and probably on
the average just as efficient) as his orginal solution.



P.S., I'm surprised none of the responses I've seen so far
have dealt with the real issue, which shows how irrelevant
the discussion of esoteric details of order of evaluation
in C implementations is to the real problem.
-- 
				J. Wong		ucbvax!mtxinu!rtech!wong

****************************************************************
You start a conversation, you can't even finish it.
You're talking alot, but you're not saying anything.
When I have nothing to say, my lips are sealed.
Say something once, why say it again.		- David Byrne



More information about the Comp.lang.c mailing list