• dmad@programming.dev
    link
    fedilink
    arrow-up
    5
    ·
    edit-2
    1 year ago

    xor has the property x ^ x = 0, and x ^ 0 = x. So, x ^ x ^ y = y

    a' = a ^ b
    b' = b ^ a' = b ^ (a ^ b) = a
    a'' = (a ^ b) ^ a = b
    

    This is pretty clever, I’ve never seen this for a swap.

    • ActuallyRuben@actuallyruben.nl
      link
      fedilink
      arrow-up
      2
      ·
      1 year ago

      Couldn’t have explained it better myself. I don’t remember where exactly I first read about this trick, but it’s mainly useful in C or Assembly, as you don’t have to resort to using a third variable/register.