swap(x,y)

Chris Torek chris at mimsy.UUCP
Wed Aug 23 00:25:22 AEST 1989


Before anyone charges off to `correct' Herman Rubin....  (Note: I have
compressed these vertically and elided some text.)

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:
>>	x += y; y = x - y; x -= y;

In article <1524 at l.cc.purdue.edu> cik at l.cc.purdue.edu (Herman Rubin) writes:
>... for switching registers in a tights situation on a machine without
>instruction overlap, it is likely to be as fast as anything.  One needs
>three instructions, and since the operations may be as fast as moves,
>no time is lost, compared to
>
>	temp = y; y = x; x = temp;
>
>except that if x and y are the same, the second will work but not the first.

Again, before you `correct' this: that is, not that x and y have the
same *value*, but rather that x and y name the same storage location:

	int a = 1, *x = &a, *y = &b;
	*x += *y; *y = *x - *y; *x -= *y;

which winds up setting `a' to 0, rather than swapping it with itself.

The xor-trick is more often seen in the `swap registers in a tight
situation' situation than the add/subtract trick (it has the advantage
of working on two-address machines, as well).
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list