SWAP macro

Joseph D. Shapiro shap at bunker.UUCP
Thu Jun 26 22:37:56 AEST 1986


In article <1577 at brl-smoke.ARPA> Schauble at MIT-MULTICS.ARPA (Paul Schauble) writes:
>I've gotten lots of respones to my request for a form of the macro that
>would make
>  swap(*a++, *b++);
> work.  Almost all of them missed the point.  The swap requires a
>temporary.  Generating that temporary requires knowing the type.
>Several of the solutions would work fine if *a and *b were int's, but I
>never said that.
>

ok, then, how about

#define swap(x,y) \
	{ \
		char * px = (char *)&(x); \
		char * py = (char *)&(y); \
		char t; \
		int i; \
		for (i=sizeof(x); i; i--) \
		{ \
			t = *px; \
			*px++ = *py; \
			*py++ = t; \
		} \
	}

Note that the sizeof(x) is a compiler constant and will not generate any
code which might induce a side effect.

Also, no flames about using char pointers, please, such use is
guarenteed both in K&R and ANSI.

Let me also say that I am neutral on the typeof() debate, I did
this just for the challenge.
			
For the doubtful, here is a working program.  I have chosen x and y
to be structs to remove any (most anyway) doubt.  Program passes lint.

------ cut here ----

#define swap(x,y) \
	{ \
		char * px = (char *)&(x); \
		char * py = (char *)&(y); \
		char t; \
		int i; \
		for (i=sizeof(x); i; i--) \
		{ \
			t = *px; \
			*px++ = *py; \
			*py++ = t; \
		} \
	}

#define peek(exp) printf("%s(%d): %s == %d\n",__FILE__,__LINE__,"exp",exp)

struct sss
{
	int i;
	long l;
	char c;
} a,b, *pa, *pb;

main()
{
	a.i=1;
	a.l=2;
	a.c=3;

	b.i=11;
	b.l=22;
	b.c=33;

	peek(a.i);
	peek(a.l);
	peek(a.c);
	peek(b.i);
	peek(b.l);
	peek(b.c);

	pa= &a;
	pb= &b;

	peek(pa);
	peek(pb);

	swap( *pa++, *pb++ );

	peek(pa);
	peek(pb);

	peek(a.i);
	peek(a.l);
	peek(a.c);
	peek(b.i);
	peek(b.l);
	peek(b.c);
}
-- 
-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_

Joseph D. Shapiro			"He who hesitates
Bunker Ramo Information Systems		 is lunch"

...ittatc!bunker!shap
...decvax!bunker!shap



More information about the Comp.lang.c mailing list