Article View: comp.std.c
Article #1691Re: Why no logical XOR operator
From: Stan Brown, Oak Road Systems
Date: Thu, 13 Sep 1990 19:51
Date: Thu, 13 Sep 1990 19:51
60 lines
2522 bytes
2522 bytes
In article <1990Sep12.154515.18460@druid.uucp>, darcy@druid.uucp (D'Arcy J.M. Cain) writes:
>>from: darcy@druid.uucp (D'Arcy J.M. Cain)
>
> Recently I had occasion to write something like the following code:
>
> if ((!x && (y & z)) || (x && !(y & z))
> something();
>
> Which would have been simpler as:
>
> if (x ^^ (y & z))
> something();
>
> If there was such a thing as a '^^' operator. Does anyone know why C left
> out the logical XOR operator?
BTW, did you mean y & z or y && z?
My first thought was, What about
if ( x ? !(y&z) : (y&z) )
Hmm, still pretty ugly, though at least it doesn't repeat both tests.
I could write it
if ( (y&z) ? !x : x )
to repeat only the shorter test. However ...
Buzzing around in the back of my head, like a bluebottle at a dusty
window, was the idea of capitalizing on the fact that ! returns 1 or 0
always. Okay, I thought, y&z may as well be replaced by a single
variable, so set yz for y&z (or y&&z). Now the expression is
if ( (!x && yz) || (x && !yz) )
A quick truth table, using 1 to mean "anything non-zero".
x yz !x !yz desired result
1 1 0 0 0
1 0 0 1 1
0 1 1 0 1
0 0 1 1 0
Hmm, looks mighty familiar. In fact the desired result is !x ^ !yz, or in
the original terms of the problem,
if ( !x ^ !(y & z) )
So the reason there's no "logical exclusive or" is that bitwise exclusive
ORing the negated quantities gives the same result.
BTW, (1) I'd probably comment that !^! construction, because it looks
weird, and (2) I'd ask somebody else to review it to make sure I didn't
have some dumb goof. (3) On proofreading this posting, I think I'd
probably go back to my first thought, above, because IMHO it's clearer.
Stan Brown, Oak Road Systems, Cleveland, Ohio, U.S.A. (216) 371-0043
The opinions expressed are mine. Mine alone! Nobody else is responsible for
them or even endorses them--except my cat Dexter, and he signed the power of
attorney only under my threat to cut off his Cat Chow!
Technical Details
Message-ID:
<913.26ef9d0e@iccgcc.decnet.ab.com>Path:
arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!wuarchive!uunet!abvax!iccgcc!brownsReferences:
<1990Sep12.154515.18460@druid.uucp>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!wuarchive!uunet!abvax!iccgcc!browns From: browns@iccgcc.decnet.ab.com (Stan Brown, Oak Road Systems) Newsgroups: comp.std.c Subject: Re: Why no logical XOR operator Message-ID: <913.26ef9d0e@iccgcc.decnet.ab.com> Date: 13 Sep 90 19:51:53 GMT References: <1990Sep12.154515.18460@druid.uucp> Lines: 60