swap() macro

Geoff Kimbrough geoff at ism780c.UUCP
Fri Jun 20 04:21:54 AEST 1986


In article <1201 at brl-smoke.ARPA> Schauble at 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.



More information about the Comp.lang.c mailing list