swap() macro
Andrew Koenig
ark at alice.UucP
Mon Jun 23 00:27:11 AEST 1986
> #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.
On the other hand, if you forget a semicolon:
if (x < y)
swap (x, y)
printf ("%d %d\n", x, y);
you will spend a long time wondering why it doesn't print anything.
Of course, if you write in C++, you can say:
inline void swap (int& x, int& y)
{
register int t = x;
x = y;
y = t;
}
and be done with it. It's a true function, the compiler checks
types for you, you can define several swap functions for different
types, and so on.
More information about the Comp.lang.c
mailing list