-7
$\begingroup$

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?

$\endgroup$
1
  • 8
    $\begingroup$ This is not a research-level question. $\endgroup$ Feb 10 '12 at 5:40
1
$\begingroup$

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}

$\endgroup$
7
  • 3
    $\begingroup$ Please don't answer such questions. Doing so invites more questions which are not suitable for this forum. $\endgroup$ Feb 10 '12 at 9:06
  • 3
    $\begingroup$ 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. $\endgroup$
    – Kai
    Feb 10 '12 at 10:55
  • $\begingroup$ 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). $\endgroup$ Feb 10 '12 at 13:27
  • 1
    $\begingroup$ Also, note that when $x = y$ this command sets *x = *y = 0. You need to check if x = y as a special case. $\endgroup$ Feb 10 '12 at 13:28
  • $\begingroup$ @DavidHarris You are right, nevertheless it can be fixed: *x = *x + *y; *y = *x - *y; *x = *x - *y; (for ints only). $\endgroup$ Feb 10 '12 at 14:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.