swap(x,y)

medewerker ast condict at cs.vu.nl
Mon Sep 11 21:18:18 AEST 1989


In article <1989Sep6.061301.17629 at algor2.algorists.com> jeffrey at algor2.UUCP (Jeffrey Kegler) writes:
 |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.

As has been described several times in this newsgroup, this defect can be
avoided by using one of the following two equivalent definitions instead of
(B), above:

    B1) #define swap(x,y) do {int tmp; tmp = x; y = tmp; x = y; } while (0)
    B2) #define swap(x,y) if (1) {int tmp; tmp = x; y = tmp; x = y; } else 0

This has the advantage of producing a syntax error if the use of swap is not
followed by a ';', just as a real function call would.  It has the disad-
vantage of looking silly and inefficient to the uninitiated.  It should,
however, generate the same code as without the extraneous statement, on any
reasonable C compiler.

Mike Condict			condict at cs.vu.nl
Vrije University



More information about the Comp.lang.c mailing list