swap() macro

Steve Villee steve at anasazi.UUCP
Sat Jun 21 03:44:48 AEST 1986


> Can someone construct a version that makes
> 
>     int *a, *b;
>     swap (*a++,*b++);
> 
> work right?
> 
>           Paul
>           Schauble at MIT-Multics.arpa

--------------------------------

#define swap(x, y) \
  if (1) \
  { \
    register int *xp, *yp, t; \
    xp = &(x); \
    yp = &(y); \
    t = *xp; \
    *xp = *yp; \
    *yp = t; \
  } \
  else

--------------------------------

The "if (1) ... else" allows the user to put a semicolon after the macro
invocation, and makes code such as

  if (today == tuesday)
    swap(*a++, *b++);
  else
    swap(*c++, *d++);

work correctly.

--- Steve Villee (ihnp4!mot!anasazi!steve)
    International Anasazi, Inc.
    7500 North Dreamy Draw Drive, Suite 120
    Phoenix, Arizona 85020
    (602) 870-3330



More information about the Comp.lang.c mailing list