Re: (TC304.2308) translating logical operators

From: John Cowan (
Date: Fri Jun 09 2000 - 14:08:12 EDT

On Fri, 9 Jun 2000, Doug Ewell wrote:

> It is true that "&" and "|" always evaluate both arguments, whereas
> "&&" and "||" evaluate the second argument only if necessary according
> to the rule described by John. However, that is not the primary
> difference between the two types of operators. C/C++ programmers get
> into trouble confusing "&" with "&&" much more because of the bitwise
> vs. logical difference than because of whether the second operand is
> evaluated.

Well, the historical truth is somewhere between. In Dennis Ritchie's
paper on the history of C (
he writes:

# In BCPL and B [the immediate ancestors of C],
# the evaluation of expressions depends on context: within if and
# other conditional statements that compare an expression's value
# with zero, these languages place a special interpretation on the
# and (&) and or (|) operators. In ordinary contexts, they operate
# bitwise, but in the B statement
# if (e1 & e2) ...
# the compiler must evaluate e1 and if it is non-zero, evaluate e2,
# and if it too is non-zero, elaborate the statement dependent on
# the if. The requirement descends recursively on & and | operators
# within e1 and e2. The short-circuit semantics of the Boolean
# operators in such `truth-value' context seemed desirable, but the
# overloading of the operators was difficult to explain and use. At
# the suggestion of Alan Snyder, I introduced the && and || operators
# to make the mechanism more explicit.

In any event, Ada's ancestor is Pascal, in which full evaluation is the
rule, making code like "if i < r_upb and r[i] > 0" useless. So
the introduction of "and then" and "or else" into Ada bypassed
this problem.

> In any event, relying on the conditional evaluation or non-evaluation
> of the second operand in "&&" and "||" is considered tricky C and best
> avoided, although there are some cases where it is indispensible.

Humph. Any feature is "tricky" to those who don't understand it.
Failing to grasp the Buddha-nature of && and || disqualifies one
as a competent C programmer, IMNSHO. Now Duff's device
*that's* tricky.

John Cowan                         
	"You need a change: try Canada"  "You need a change: try China"
		--fortune cookies opened by a couple that I know

This archive was generated by hypermail 2.1.2 : Tue Jul 10 2001 - 17:21:03 EDT