The Swap Trap


When you are learning programming, you quickly find out that your common sense approaches have to be modified to deal with the facts. For instance, when you are told to write a routine to swap two values, your common sense tells you what to write, and assures you there's no reason to check your work, and so you write something like:


        subroutine swap2 ( x, y )
        real x
        real y

        x = y
        y = x

        return
        end
      
When, to your horror, you discover that your routine does not work, it takes a while to understand that you've just encountered a mental blind spot. Some people never get past this kind of problem, but you just made a mental note: (Note to self: swapping requires a temporary variable, and the values hop around in a daisy chain.)

After a while, things settle down. You know the best algorithm for sorting, you know how to compute the determinant of a matrix if you really have to, and you know how to write a swap routine:


        subroutine swap2 ( x, y )
        real x
        real y
        real temp

        temp = x
        x = y
        y = temp

        return
        end
      
and the existence of that irritating little temp is the price we pay for our use of the assignment operator.

But would you believe that it's possible to write a swap routine, similar to the ones above, that uses no temporary variables at all? Why didn't anyone tell us this?

I give up, show me the solution.


Last revised on 11 February 2001.