Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!watmath!clyde!burl!ulysses!allegra!mit-eddie!genrad!decvax!ittatc!bunker!shap From: shap@bunker.UUCP (Joseph D. Shapiro) Newsgroups: net.lang.c Subject: Re: SWAP macro Message-ID: <1212@bunker.UUCP> Date: Thu, 26-Jun-86 08:37:56 EDT Article-I.D.: bunker.1212 Posted: Thu Jun 26 08:37:56 1986 Date-Received: Sat, 28-Jun-86 05:21:49 EDT References: <1577@brl-smoke.ARPA> Reply-To: shap@bunker.UUCP (Joseph D. Shapiro) Organization: Bunker Ramo, Trumbull Ct Lines: 106 In article <1577@brl-smoke.ARPA> Schauble@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