The Swap Trap
Solution


The following code will interchange the values in X and Y, and uses no temporary variables:


        subroutine swap2 ( x, y )
        real x
        real y

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

        return
        end
      
It may be hard to believe this, but just work out what happens when you start with X being 10 and Y being 7, for instance.

So why does no one use a swap routine like this? Well, first of all, computer memory isn't so expensive that it's worth our while to sacrifice clarity for space. Secondly, using a temporary variable, we avoid doing arithmetic, which takes time, and which can introduce slight roundoffs in our results. We'd be right to be upset if, after we swapped the values X and Y, they had been slightly changed. Finally, this technique wouldn't generalize very well if we were swapping items that were not numeric.

Back to The Swap Trap.


Last revised on 11 February 2001.