how to swap the value of two variables without an auxilary (helping) variable [closed]

how to swap the value of two variables without an auxilary (helping) variable ?

swap(int *x,int *y) { int h = *x; *x = *y; *y = h; }

how can we do it without introducing h?

• This is not a research-level question. Feb 10 '12 at 5:40

1 Answer

One solution is using XOR as following:

$$\begin{eqnarray} *x = (*x)\wedge(*y);\tag{1}\\ *y = (*x)\wedge(*y);\tag{2}\\ *x = (*x)\wedge(*y)\tag{3}; \end{eqnarray}$$

• Please don't answer such questions. Doing so invites more questions which are not suitable for this forum. Feb 10 '12 at 9:06
• Knowing how to do this while knowing not much else about programming can be harmful. Many years ago when I was a 2nd year student coding for a huge project as a summer job, I made a C macro for swapping based on the above. Since swap dominated the computation, there was a non-negligible blowout in code size after macro expansion and performance penalty, puzzling the senior members of the team – until they saw my macro.
– Kai
Feb 10 '12 at 10:55
• The problem with this solution is that it is not type-safe. This solution implicitly assumes that there is some encoding of $x, y$ as bits. As far as I know, there is no general type-safe method of swapping two values. (Although some programming languages contain a special command to swap elements). Feb 10 '12 at 13:27
• Also, note that when $x = y$ this command sets *x = *y = 0. You need to check if x = y as a special case. Feb 10 '12 at 13:28
• @DavidHarris You are right, nevertheless it can be fixed: *x = *x + *y; *y = *x - *y; *x = *x - *y; (for ints only). Feb 10 '12 at 14:13