Re: (TC304.2308) translating logical operators

From: Doug Ewell (
Date: Fri Jun 09 2000 - 12:48:57 EDT


John Cowan <> wrote about Ada:

> With "and then", the right-hand operand is not computed at run-time
> if the left-hand operand is known to be false, since the result must
> be false. With "and", this is not the case.
> Similarly, "or else" does not examine its right-hand operand if the
> left-hand operand is known to be true.
> C/C++/Java/Perl programmers know this under the names of "&" vs "&&"
> and "|" vs. "||" operators.

This isn't quite how it works in C and C++. "&" and "|" are bitwise
operators that perform the intersection and union respectively of the
two operands, one bit at a time. For example, (5 & 6) == 4 and
(5 | 6) == 7.

"&&" and "||" are logical operators that evaluate the two operands (as
necessary; see below) for their zero-ness or non-zero-ness and return
either 1 or 0 as appropriate. For example, (5 && 6) == 1 and (5 || 6)
== 1.

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

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.

-Doug Ewell
 Fullerton, California


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