# Variable swapping question

Discussion in 'C Programming' started by Chad, Jul 5, 2008.

Given something like the following

void swap(int *x, int *y)
{
int temp;

temp = *x;
*x = *y;
*y = temp;
}

How does having a temp variable allow for anything to safely swap with
itself? Like for example x = 10 and y = 10. What would happen in the
absence of temp?

2. ### Keith ThompsonGuest

I assume you mean *x == 10 and *y == 10.

But what I suspect you *really* mean is x == y, i.e., x and y both
point to the same object. The swap function above works just fine in
that case; the value is saved to temp, then copied over itself, then
restored from temp. Is there some potential problem you had in mind?
Well, you couldn't do the first and third assignments, so it wouldn't
be able to swap anything. Or did you have something else in mind
instead of temp? Perhaps something like question 3.3b of the
comp.lang.c FAQ, <http://c-faq.com/>?

Keith Thompson, Jul 5, 2008

I was just curious why you needed temp. I did the following

m-net% more swap.c
#include <stdio.h>
void swap(int *x, int *y)
{
int temp;

/*temp = *x ; */
*x = *y;
/* *y = temp; */

}

int main(void)
{
int a = 10;
int b = 20;

swap(&a, &b);

printf("After swap: a=%d , b=%d\n", a, b);

return 0;
}
m-net% ./swap
After swap: a=20 , b=20
m-net%

And now just thought about what you said. Now I need about a hour for
it to really sink in.

4. ### Ron FordGuest

I see no mystery in this result; you'll find that this type of swap needs a
temp. You can swap in other ways, say, using a macro, but the pointer
version is simply better all around.

Ron Ford, Jul 5, 2008