[This is part of my reply to someone who asked how to swap two values without using a third object.]

From: scs@eskimo.com (Steve Summit)
Subject: Re: Swapping two values
Date: Fri, 13 Jun 1997 07:27:59 -0700 (PDT)
Message-Id: <199706131427.HAA06631@mail.eskimo.com>

You wrote:
> I have a question for you :
> I need to swap the value of two scalar's without using a third object.

There are two possible reasons you might be asking me this question:
1. This requirement is part of some project concerning your employment.
2. This is a homework or examination question.

If the former, please go back and convince the architect or manager who has imposed this requirement to reconsider. The trick for swapping values without using temporaries is useful only in assembly language, when for some reason registers are in short supply. The trick has no place in a higher-level language such as C, because temporary variables are essentially free. If you're using C, the right way to swap two values a and b is to use a temporary t:

	t = a;
	a = b;
	b = t;

Using the trick would only make your program slightly larger, slightly slower, and slightly harder to understand.

If the latter, I normally do not give people the answers to homework problems, but since this question is ill-advised, I'm willing to make an exception.

If a and b are integers, you can swap them by using this curious set of exclusive-or operations:

	a ^= b;
	b ^= a;
	a ^= b;

But this works only if a and b are integers, and it has an additional disadvantage, which is that if for some reason you have pointers to the integers you want to swap, such that you're tempted to write

	*p1 ^= *p2;
	*p2 ^= *p1;
	*p1 ^= *p2;

then in the case where p1 == p2, you'll zero out both *p1 and *p2. (The case could arise if you wrote something like

	swap(&a[i], &b[j]);
in the context of a sorting routine, and i==j.)

If a and b are floating-point variables, I think there are triple sequences of additions and subtractions which will accomplish a swap, but they're all subject to overflow.

Again, these ``tricks,'' even if they work, are likely to be significantly slower and bulkier than the obvious three-assignment swap using a temporary. These tricks are intellectual curiosities only; they offer no advantages over the more obvious swap; they have virtually no place in modern programming.

If, in fact, this was a homework question, please request your instructor not to assign it in the future. It is essentially meaningless and misleading; it serves mostly to induce students to use these tricks in real programs, where they have no place. Also, if your instructor offers as a solution to this question the version of the exclusive-or trick expressed as

	a ^= b ^= a ^= b;
please inform your instructor that this expression is undefined in C.

Steve Summit