# Thread: Swap function using no temp variable

1. ## Swap function using no temp variable

i was assigned in my programming class to make a function of the form int swap(&a, &b) that doesnt use a third variable in the swap. i have pondered on this for a few hours and i cant think of anything. any help would appreciated. thanks in advance

2. You can do this using bit manipulation, XOR-ing the values. I've
never needed to do this, but I believe it's something like:

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

Something like that.

Quzah.

3. >Something like that.
Yea, it's a common trick. There's no way to use it correctly, despite what some will tell you. Use a temporary variable, is it really that much harder?

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

Good Practice
temp = a;
a = b;
b = temp;

Seems just as easy to me, and you don't suffer scary code syndrome.

-Prelude

4. yeah I've seen this way, but it doesn't always work..
a^=b^=a^=b;

here's another way (simply mathematical)

a += b;
b = a - b;
a -= b;

5. >yeah I've seen this way, but it doesn't always work..
>a^=b^=a^=b;
Of course not, the value of each variable is modified more than once between sequence points, which results in undefined behavior.

-Prelude

Popular pages Recent additions