May 08 2007
Digression into Swaps
Did you know you can swap the value of two variables without temp??
$a = $a + $b;
$b = $a - $b;
$a = $a - $b;
I wish I were so clever as to come up with that on my own. Still, I post it here to spark the imagination of those who find it as fascinating as I.
6 Responses to “Digression into Swaps”
Leave a Reply
You must be logged in to post a comment.
I should point out that this post arose from a pasta gratin, the baking of which required a swap of two pans to different racks in the oven. Many thanks to Jeremy for englightening us on this subject.

If you worry about arithmetic overflow, XOR comes to the rescue
#include
main() {
int a =5;
int b=7;
a = a ^b;
b = b ^a;
a = a^ b;
printf (”%d %d\n”, a , b);
}
Neat, I can vaguely remember doing that once in a programming class two years ago. Now it will hopefully stay on my mind!
Oh, that’s cool! This:
($a, $b) = ($b, $a);
would also do the job (in Perl) and might be a bit more readable
That is cool… not sure if C++ compilers would keep the optimization in however - if you really need to cut the extra variable out it might be best to do it in assembly.
Am I ever glad to program in sane languages that can do swapping on one line, like Perl (but Python is much better).