-->

When would you swap two numbers without using a th

2019-02-24 03:27发布

问题:

I have read several sources that discuss how to swap two numbers without using a third variable. These are a few of the most relevant:

  • How do you swap two integer variables without using any if conditions, casting, or additional variables?
  • Potential Problem in "Swapping values of two variables without using a third variable"
  • Swap two integers without using a third variable
  • http://www.geeksforgeeks.org/swap-two-numbers-without-using-temporary-variable/

I understand why it doesn't make sense to use the described methods in most cases: the code becomes cluttered and difficult to read and will usually execute more slowly than a solution utilizing a third "temp" variable. However, none of the questions I have found discuss any benefits of the two-variable methods in practice. Do they have any redeeming qualities or benefits(historical or contemporary), or are they only useful as obscure programming trivia?

回答1:

At this point it's just a neat trick. Speed-wise if it makes sense though your compiler will recognize a normal swap and optimize it appropriately (but no guarantees that it will recognize weird xoring and optimize that appropriately).



回答2:

Another strike against xor is that if one variable alias the other, xor’ing them will zero both out. Since you’ll have to check for and handle this condition, you’ll have extra code involved – probably by using the third variable method.

You could also try adding and subtracting values… except that you’d have to check for and handle overflow, which would involve more code (probably the third variable method). Multiplication and division have the same flaw, but more importantly, there’s the exquisite delight of representing fractions in binary (so this wouldn’t work in the first place).

Edit: D’oh, sorry for the thread necromancy… got so caught up in following links that I forgot to check the dates.