Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there ever a point to swap two variables without using a third?

Tags:

I know not to use them, but there are techniques to swap two variables without using a third, such as

x ^= y; y ^= x; x ^= y; 

and

x = x + y y = x - y x = x - y  

In class the prof mentioned that these were popular 20 years ago when memory was very limited and are still used in high-performance applications today. Is this true? My understanding as to why it's pointless to use such techniques is that:

  1. It can never be the bottleneck using the third variable.
  2. The optimizer does this anyway.

So is there ever a good time to not swap with a third variable? Is it ever faster?

Compared to each other, is the method that uses XOR vs the method that uses +/- faster? Most architectures have a unit for addition/subtraction and XOR so wouldn't that mean they are all the same speed? Or just because a CPU has a unit for the operation doesn't mean they're all the same speed?

like image 826
Celeritas Avatar asked Oct 09 '14 07:10

Celeritas


People also ask

Can we swap 2 variables without a third one?

Given two variables, x, and y, swap two variables without using a third variable. The idea is to get a sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from the sum.

Which is the correct way to swap value of two variables?

Swap Numbers Using Temporary Variable In the above program, the temp variable is assigned the value of the first variable. Then, the value of the first variable is assigned to the second variable. Finally, the temp (which holds the initial value of first ) is assigned to second . This completes the swapping process.


1 Answers

These techniques are still important to know for the programmers who write the firmware of your average washing machine or so. Lots of that kind of hardware still runs on Z80 CPUs or similar, often with no more than 4K of memory or so. Outside of that scene, knowing these kinds of algorithmic "trickery" has, as you say, as good as no real practical use.

(I do want to remark though that nonetheless, the programmers who remember and know this kind of stuff often turn out to be better programmers even for "regular" applications than their "peers" who won't bother. Precisely because the latter often take that attitude of "memory is big enough anyway" too far.)

like image 128
Erwin Smout Avatar answered Jan 01 '23 22:01

Erwin Smout