In article <news:cunr7tbfk18.fsf@zero-based.org>
Martin Dickopp <expires-2004-06-30@zero-based.org> writes:[color=blue]
>[The token-pasting] technique [using the names of the variables
>to be swapped] only works if the second and third macro arguments are
>identifiers. Otherwise, the pasting doesn't yield a valid preprocessor
>token, e.g.
>
> int a [] = {1, 9};
> SWAP (int, a [0], a [1]);
>
>doesn't work.[/color]
Indeed.
[color=blue]
>It also "pollutes" the namespace with `PASTE' and `PASTE_'. If that is
>acceptable, why not go for the following much simpler solution:
>
> #define SWAP(t, a, b) do { t PASTE = (a); \
> (a) = (b); \
> (b) = PASTE; } while (0)[/color]
My usual method is just to write such swaps in-line, e.g., when
expanding a specialized sort function in C (in C++ one would just
use templates; and in Ada one would use generics, and so on; in
these languages the problem has a "language-preferred" solution).
If for some reason a swap macro appeals, one could perhaps do away
with the "type" parameter entirely, and supply instead a "temporary
variable" parameter:
#define SWAP(t, a, b) (t = (a), (a) = (b), (b) = t)
...
int a[N];
int swaptmp;
...
SWAP(swaptmp, a[i], a[j]); /* cf. SWAP(int, a[i], a[j]) */
In this version of the macro, I deliberately did not parenthesize
occurrences of the name "t" because it is supposed to be a simple
variable of the appropriate type.
If one wishes to reduce the scope of the variable to just the braces
introduced by a do-while(0) (e.g., to assist a compiler in
optimization) there is another variant of this method:
#define SWAP(t, v, a, b) \
do { t v = (a); (a) = (b); (b) = v; } while (0)
...
SWAP(int, swaptmp, a[i], a[j]);
So far, however, it has been my experience that compilers smart
enough to optimize swaps into machine-level XCHG instructions (or
equivalent) are also smart enough to do dataflow and lifetime
analysis on variables, so that they can already determine that
the "swaptmp" variable's value persists only for the one source
line.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it
http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.