swap(x,y)

Jeffrey Kegler jeffrey at algor2.algorists.com
Wed Sep 6 16:13:01 AEST 1989


One thing that makes

A)   #define swap(x,y) (x ^= y, x ^= y ^= x)

seem more attractive than

B)   #define swap(x,y) {int tmp; tmp = x; y = tmp; x = y; }

is the syntax.

Consider

  if (...) swap(x,y);
  else { do stuff ...; swap(a,b); }

which the Solution A allows, but which won't work with the Solution B,
unless the first semi-colon is omitted.  The second last semi-colon in
the above example is misleading, but overwise harmless.

Even more disastrous for B is

  for (tweedledee=1, tweedledum=0; !done; swap(tweedledee, tweedledum)) {
    stuff ...

Notes:
1) Both solutions are taken from other postings and not tested.
2) Solution A should have more parentheses, they are omitted for clarity.
3) It is assumed all variables are ints.
4) I think the idea of a global temporary to make Solution B an expression
is unworkable if your global temporary has its name used elsewhere
and ugly when it does work.
5) Defines are prefered because inlining the solutions makes the code harder
to read, and the overhead of a function call to swap two ints is often not
justifiable.
-- 

Jeffrey Kegler, Independent UNIX Consultant, Algorists, Inc.
jeffrey at algor2.ALGORISTS.COM or uunet!algor2!jeffrey
1762 Wainwright DR, Reston VA 22090



More information about the Comp.lang.c mailing list