jerbil@ultra.com (Joseph Beckenbach {Adapter Software Release Engr}) (04/18/91)
In <157@revcan.UUCP> darren@revcan.UUCP (Darren Morbey) writes,
asking for a macro returning XOR of its arguments, evaluating once and
only once. I've not worked out a more elegant solution for my toolbag,
alas:
------
#include <stdio.h>
#define XOR( a, b ) \
( t1=((a)!=0), t2=((b)!=0), ( (t1 && t2) ? 0 : (t1 || t2) ) )
int
main( )
{
int t1, t2;
printf( "0 0 %d\n", XOR(0,0) );
printf( "0 1 %d\n", XOR(0,1) );
printf( "1 0 %d\n", XOR(1,0) );
printf( "1 1 %d\n", XOR(1,1) );
}
------
Output:
0 0 0
0 1 1
1 0 1
1 1 0
The variables t1 and t2 need to be in-scope when XOR is used --
I usually place these as file-scope static globals (documented, of course).
It uses the standard convention of representing boolean "false" as 0, "true"
as non-0. Note that this takes pointers as well, and will interpret
(type*)NULL as "false". Why this might be useful, I don't know....
Joseph Beckenbach
journeyman programmer
--
Joseph Beckenbach jerbil@ultra.com VEGGIES FOREVER!
(aka Joseph d'Aquitaine, aka the Stainless Steel Jerbil)
work 408-922-0100 x246 home 408-983-2944
jerbil@ultra.com (Joseph Beckenbach {Adapter Software Release Engr}) (04/19/91)
Following up my own article here, and apologies for missed names: > In <157@revcan.UUCP> darren@revcan.UUCP (Darren Morbey) writes, >asking for a macro returning XOR of its arguments, evaluating once and >only once. I've not worked out a more elegant solution for my toolbag, ... but I've had a light flurry of mail with comments, including one from the Netherlands pointing out that XOR(a,XOR(b,c)) would fail using my implementation. Serves me right for reusing old code without doing a double-check of other things! :-) Another sent me the macro #define XOR(o,_) ((o)?!(_):(_)) which "does the right thing". Another macro for toolbox.h :-) Joseph Beckenbach journeyman programmer (still working towards craftsman status) -- Joseph Beckenbach jerbil@ultra.com VEGGIES FOREVER! work 408-922-0100 x246