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.


Author: Lucello

Something about me?

6 thoughts on “Digression into Swaps”

  1. 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.


  2. If you worry about arithmetic overflow, XOR comes to the rescue


    main() {
    int a =5;
    int b=7;

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

    printf (“%d %d\n”, a , b);

  3. Neat, I can vaguely remember doing that once in a programming class two years ago. Now it will hopefully stay on my mind!

  4. Oh, that’s cool! This:

    ($a, $b) = ($b, $a);

    would also do the job (in Perl) and might be a bit more readable ­čÖé

  5. 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.

  6. Am I ever glad to program in sane languages that can do swapping on one line, like Perl (but Python is much better).

Leave a Reply