Topic: Why no logical XOR operator
Author: Warner Losh <imp@village.org>
Date: 1995/08/21 Raw View
Distribution:
: I'm wondering why there isn't a logical XOR operator (eg. ^^)
: though there is a bitwise one (ie. ^).
The '!=' operator is logically the same as XOR. It produces the same
truth table for bool values as you'd expect an xor operator to:
a != b
a/b true false
true false true
false true false
However, the precidence of this operator is not what you'd want it to
be to really use XOR. Eg
if (a != b || c !=d)
parses "correctly" but
if (a != b != c != d)
doesn't. This is easy to fix with parens:
if ((a != b) != (c != d)).
However, since ^ has a lower precedence than !=, you could write
something like
if (a != b ^ c != d)
and have no need for parens.
There can be no short circuit done for this operator, since you can't
know the result of the operator until you've evaluated both sides.
Maybe that is why it isn't in the language. I was once told that C
had both | and || because one was optimized and the other wasn't.
Since it is impossible to optimize xor, there is no ^^ operator. I'm
not sure how true this actually is.
Warner
---
[ comp.std.c++ is moderated. Submission address: std-c++@ncar.ucar.edu.
Contact address: std-c++-request@ncar.ucar.edu. The moderation policy
is summarized in http://dogbert.lbl.gov/~matt/std-c++/policy.html. ]
Author: jesper@dna.lth.se (Jesper Larsson)
Date: 1995/08/23 Raw View
In article <MATT.95Aug21165410@physics2.Berkeley.EDU>, Warner Losh <imp@village.org> writes:
>: I'm wondering why there isn't a logical XOR operator (eg. ^^)
>: though there is a bitwise one (ie. ^).
>
>The '!=' operator is logically the same as XOR. It produces the same
>truth table for bool values as you'd expect an xor operator to:
[deletia]
>There can be no short circuit done for this operator, since you can't
>know the result of the operator until you've evaluated both sides.
>Maybe that is why it isn't in the language. I was once told that C
>had both | and || because one was optimized and the other wasn't.
>Since it is impossible to optimize xor, there is no ^^ operator. I'm
>not sure how true this actually is.
The optimization stuff is nonsense. The difference is that | is bit-
wise, and || is a logical operator that knows only two values: zero
and non-zero. Hence,
(1 | 2) == 0, i.e. false if interpreted as boolean, but
(1 || 2) == 1, i.e. true.
The != operator can only be used as xor if you are certain that
logical values are never represented by any other integers than
0 and 1.
Jesper Larsson ,,, jesper@dna.lu.se
Dept. of Computer Science, Lund University (o o) +46 46 22 24908
-------------------------------------------oOO-(_)-OOo----------------
``Bad programming practice can lead to death.'' (P.J. Plauger)
---
[ comp.std.c++ is moderated. Submission address: std-c++@ncar.ucar.edu.
Contact address: std-c++-request@ncar.ucar.edu. The moderation policy
is summarized in http://dogbert.lbl.gov/~matt/std-c++/policy.html. ]