Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would you swap two numbers without using a third variable?

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?

like image 824
SemperMelior Avatar asked Feb 13 '23 10:02

SemperMelior


1 Answers

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

like image 120
U2EF1 Avatar answered Apr 29 '23 06:04

U2EF1