swap() macro

der Mouse mouse at mcgill-vision.UUCP
Wed Jun 25 11:49:00 AEST 1986


In article <1228 at brl-smoke.ARPA>, rbj at icst-cmr (Root Boy Jim) quotes
> 	Can someone construct a version that makes
> 	    int *a, *b;
> 	    swap (*a++,*b++);
> 	work right?
and writes
> Probably not. In general, macros don't work on arguments that have side effects.

How about the following, which assumes the  arguments have addresses (no
bitfields  or  register  variables  need  apply).    I  would  advise  C
portability purists to hit n; this code is pretty gross.

#define swap(x,y) \
{ register char *t1 = (char *)&(x);	\
  register char *t2 = (char *)&(y);	\
  register int n = sizeof((x));		\
  register int i;			\
  for (i=0;i<n;i++)			\
   { *t1 ^= *t2;			\
     *t2 ^= *t1;			\
     *t1 ^= *t2;			\
    }					\
}

I *told* you it was gross.   But it should work, if not  on all machines
out there,  on a  large subclass  (let's see, byte-addressable machines,
any other restrictions folks?).
-- 
					der Mouse

USA: {ihnp4,decvax,akgua,utzoo,etc}!utcsri!mcgill-vision!mouse
     philabs!micomvax!musocs!mcgill-vision!mouse
Europe: mcvax!decvax!utcsri!mcgill-vision!mouse
        mcvax!seismo!cmcl2!philabs!micomvax!musocs!mcgill-vision!mouse
ARPAnet: utcsri!mcgill-vision!mouse at uw-beaver.arpa

"Come with me a few minutes, mortal, and we shall talk."



More information about the Comp.lang.c mailing list