## How to swap 2 variables without temp variable

October 23rd, 2007

Swapping 2 variables requires a third temp variable, this is how it is implemented with 3 variables (I have implemented this in PHP, the same logic can be used in any language):

<?php

$a = 5;

$b = 7;

$temp = $a;

$a = $b;

$b = $temp;

echo “$a : $b”;

?>

**This is how we would do this using only 2 variables**

<?php

$a = 5;

$b = 7;

$a = $a + $b; // $a becomes 12

$b = $a – $b; // $a becomes 5

$a = $a – $b; // $a becomes 7

echo “$a : $b”;

?>

Categories: Programming

How to swap 2 variables without temp variable

for eg:-

Only problem is that it only works with numbers and not strings, arrays, or other variables types. The only way you can swap those efficiently is with the third variable.

nice!

Nice post, I like how you describe the solution in simple arithmetic terms; most textbooks use the bit-mask syntax, which I find less intuitive.

Of course, one could also say that this approach of swapping 2 integer variables without a third temporary variable is in fact using a third temporary variable composed of the unused higher-order bits of the 2 input variables. If the 2 variables used enough of the bits of their data-type, this swap would not work correctly. Exactly how big the values can get and still be accurately swapped this way I leave as an exercise for the reader. ðŸ˜‰

It is very useful to all those programmers to improve logical thinking like this.