Portable XOR

Joseph Beckenbach {Adapter Software Release Engr} jerbil at ultra.com
Fri Apr 19 02:13:33 AEST 1991


	In <157 at revcan.UUCP> darren at 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 at ultra.com		VEGGIES FOREVER!
(aka Joseph d'Aquitaine,  aka the Stainless Steel Jerbil)
	work 408-922-0100 x246	 home 408-983-2944



More information about the Comp.lang.c mailing list