swap(x,y)

Thomas Hameenaho thomas at uplog.se
Fri Aug 25 22:16:55 AEST 1989


In article <MYwDEFy00WB842JEUx at andrew.cmu.edu> tg1e+ at andrew.cmu.edu (Timothy R. Gottschalk) writes:

	  To swap two variables x,y in C without using a temporary variable:

	  /* begin swap */
	  x += y;
	  y = x - y;
	  x -= y;
	  /* end swap */

	  Just curious...(this looks pretty valid) does anyone know an even
   simpler method?  I would never program this way -- it's more of a theory
   question.  I've been told that it can't be done (???).
   Tim Gottschalk
   Pgh, PA

The problem with this is the possible loss of precision.

(x += y) must not overflow x. Also if the variables are floating types
you could wind up having almost no significant bits left.


A solution that doesn't introduce any loss of precision but only
works for scalar types is:

	x ^= y;
	y = x ^ y;
	x ^= y;

--
Real life:	Thomas Hameenaho		Email:	thomas at uplog.se
Snail mail:	TeleLOGIC Uppsala AB		Phone:	+46 18 189406
		Box 1218			Fax:	+46 18 132039
		S - 751 42 Uppsala, Sweden



More information about the Comp.lang.c mailing list