Swap two integers without using a temporary variable
Here's a clever little algorithm you can use to swap two integers without using a temporary variable.
Dunno why, but I find this strangley pleasing!
Assume we have two integers, A & B, both of which have values assigned. Swap their values like this:
B := A - B;
A := A - B;
To follow this through, let:
- A0 and B0 be the original values of A and B respectively
- A1 be the value of A after line 1
- B2 be the value of B after line 2
- A3 be the value of A after line 3
After line 1:
After line 2:
= A0 + B0 - B0
After line 3:
= A0 + B0 - B2
= A0 + B0 - A0
Et voilà. Very cunning Muhammad!
EDIT: As Dalija Prasnikar pointed out in the comments, because you're adding values, there's a danger of overflow errors.
So what d'you reckon? Would you use that trick?
For me, the answer is a resounding "no way". It's clever & it intrigues me, but it's not exactly self documenting in the way swapping two integers via a temporary variable is, now is it? And the likelihood of getting that code wrong is high too.
These days, I think we can spare a few bytes for that temp variable!