Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!watmath!clyde!burl!ulysses!allegra!princeton!caip!think!nike!ucbcad!ucbvax!hplabs!sdcrdcf!ism780c!geoff From: geoff@ism780c.UUCP (Geoff Kimbrough) Newsgroups: net.lang.c Subject: Re: swap() macro Message-ID: <2595@ism780c.UUCP> Date: Thu, 19-Jun-86 14:21:54 EDT Article-I.D.: ism780c.2595 Posted: Thu Jun 19 14:21:54 1986 Date-Received: Sat, 21-Jun-86 10:34:32 EDT References: <1201@brl-smoke.ARPA> Reply-To: geoff@ism780c.UUCP (Geoff Kimbrough -- No One in Particular) Followup-To: /dev/null Organization: Interactive Systems Corp., Santa Monica, CA Lines: 33 Keywords: macros, side effects, Obfuscation In article <1201@brl-smoke.ARPA> Schauble@MIT-MULTICS.ARPA writes: >Can someone construct a version that makes > > int *a, *b; > swap (*a++,*b++); > >work right? #define SWAP(a,b) {int *A= &(a),*B= &(b),temp; temp= *A; *A= *B; *B= temp;} /* Or, for more generality. */ #define SWAP(type,a,b) {type *A = &(a),*B = &(b),temp; temp = *A; *A = *B; \ *B = temp;} /* invoked as SWAP( int, *a++, *b++ ); */ As has been pointed out, macros generally don't work when given arguments with side effects, (arguments? parameters? formals? who cares, if you understand what I mean) However, if you're careful to have the arguments appear ONLY ONCE in the expansion, you can get the results you're after. This trick only works with macros that have pointers as arguments, of course. I *don't* think this macro should be *used*, since it's got to be slower to do all the extra pointer chasing and such than to break up your statement into { swap(*a,*b); a++; b++; }. If you're concerned about having to insert extra braces, I don't even want to tadc tg qgu 0V! !$ A bust ggtt`rgug` readafg af eftaredq ufcgeeefted prggrae wat`2w`ade sgeet`afg )(/*(<--(no(kurly brace */ if ( whatever ) { hundreds of statements on several pages; with 8 space tabs, the code dissappeared off the right margin, and gradually walked back, until: } /* <-- no curly here either */ Took me over an hour just to confirm that the braces matched up.