tags:

views:

183

answers:

6

How can we take care of the overflow happening during swapping of two variables without using a third variable. I believe the XOR solution can be used only for integers. what about other variable types?

+2  A: 

XOR will work for anything you can get your XOR operator to process; it's a property of binary data, not of binary data used to represent integers.

chaos
Only if the XOR operator is actually performing an XOR operation, not if it's been overloaded to do something weird (in a language which allows operator overloading, that is).
David Zaslavsky
Ugh; yeah, that's true, and worth mentioning. Thanks.
chaos
So cast the data back to integer or char array and do the xor on the elements of that.
paxdiablo
+4  A: 

This isn't an answer but it doesn't fit in a comment.

Under what circumstances would you be running so close to the edge of your available stack storage that the additional use of a temporary variable for the swap is going to cause you difficulties?

I could see some embedded scenarios, but I'm hard pressed to imagine a scenario where you'd be so tight on stack space that this would matter (where you're not writing code in assembly language).

Larry Osterman
A: 

The XOR solution works with any type that can be bitwise copied, not just integers. However, do not XOR a variable with itself: i.e.

int x = 10;
int *p1 = &x;
int *p2 = p1;

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

/* now x == 0 :( */
rlbond
+2  A: 

By not doing it at all. The XOR swap algorithm is cool hack. It shouldn't be used in production code.

sigjuice
A: 

What's wrong with XCHG? No stack needed, no overflow(carry flag)? set either :).

RandomNickName42
Read the link in this answer and then follow footnote 2 and read that. In short - it messes up CPU cache, thus slowing things down. http://stackoverflow.com/questions/717935/stack-overflow-during-swap/717984#717984
Vilx-
OOps, I should be more careful with my click, I didn't really mean to up vote that comment, but enjoy the point ;)I re-read the Intel instruction manual for XCHG and only noticed a cache penalty on non-natural alignment access to the given operands. Maybe I'm missing something but you can inline XCHG in C/C++ for the most part, save 64bit MSVC, and I do think it satisfy's the question of not using the stack when swapping 2 variables, including the use of non-integer types. Also as other's had asked, this question does not really even seem to be language specific so Assembly is A-OK IMHO:)
RandomNickName42
A: 
a = a + b;
b = a - b;
a = a - b;

This will work for integers and float.

zdmytriv
Read the link in this answer and then follow footnote 2 and read that. In short - it takes more memory and CPU cycles than the simple swap. http://stackoverflow.com/questions/717935/stack-overflow-during-swap/717984#717984
Vilx-