Let's say I have variable holding 3 and another holding 5. I need to switch their values without another variable. How can I do it?
Asked
Active
Viewed 114 times
-3
-
4Why would you need to do that without using a separate variable? I can't see any reason for that other than for writing convoluted code. It's definitely not a real-world problem. – Jon Skeet Oct 05 '13 at 19:42
-
How **not** to do? Asks Yoda. By the way, Google, or even the search finction in the good old common Wikipeadia would have yielded you a nice and thorough answer... – ppeterka Oct 05 '13 at 19:42
-
1XOR swap idiom for low-memory chips. But a mature compiler would optimize it. – huseyin tugrul buyukisik Oct 05 '13 at 19:45
-
Sounds like an interview question. Of course you would never do this in real code. – Peter Lawrey Oct 05 '13 at 19:48
-
I saw that somewhere, promptly forgot it as complete useless.... – Tony Hopkinson Oct 05 '13 at 19:49
1 Answers
1
It can be done using bitwise XOR:
x ^= y;
y ^= x;
x ^= y;
This is known as the XOR swap algorithm (that Wikipedia article goes into detail about how this works, so I suggest you read it).
However, this isn't particularly understandable (not to mention it only works on integral types), so in nearly all contexts using a temporary variable would be preferred:
int tmp = x;
x = y;
y = tmp;

arshajii
- 127,459
- 24
- 238
- 287