Why no logical XOR operator
Stan Brown, Oak Road Systems
browns at iccgcc.decnet.ab.com
Fri Sep 14 05:51:53 AEST 1990
In article <1990Sep12.154515.18460 at druid.uucp>, darcy at druid.uucp (D'Arcy J.M. Cain) writes:
>>from: darcy at 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!
More information about the Comp.std.c
mailing list