Don’t Let the “Smart” Way to Write the Swap Function in C++ Fool You
Over the years many beginning programmers have shown me two different versions of C++ code for swapping the values of two variables. I am now starting to get tired of correcting the wrong version of the two, especially because of the disappointment that I get to see written on the face of those who thought theirs to be a very clever way of writing code. (Even if the version was correct, I don't know why they take such personal pride in the code. Obviously they have not invented the code; it has been circling the Internet or the general student community for many years, from where they have merely copied it.)
The first and the correct version for swapping values of two variables, in C++, is like this:
Simple, straightforward, and correct.
The second, wrong version goes like this:
The openly asserted advantage of this version is that one variable is saved in this case. But the real, hidden attraction is that it appears to be smartly written code. If only the version was correct too. The problem with this version, of course, is that it is useless for any type that doesn't support arithmetic operations. It works fine for integer type for example, most of the times at least. It is not guaranteed to work even for floating point variables. But what if I want to swap the values of two Colour objects? Two Shape objects? The requirement that the type support addition and subtraction operations for its objects to be swappable is very absurd.
More problems with the second "smart" version:
The call to swap() in this case should have been a "no operation" like it will be with the first version.
The code fails even for the integers when the the sum of two passed variables exceeds the maximum integer limit on that machine. The code is also needlessly unnatural. Human beings don't swap things by indulging in addition and subtraction activities. Unless a person knows that the second version works for at least the integer type (some of the times), or verifies it manually by working through it logically or with a large number of example cases, it is difficult to just see and "get" that the code indeed does the swapping operation. The second version indeed uses one less variable than the first version but at the same time uses three additional arithmetic operations.There are similar clever ways to swap two variables(using XOR operation, or macros for example), but all of them have one or more problems of similar kind. The best way to swap two variables is definitely the natural way to do it. By the way, parts of the above explanation apply to swapping variables in most other languages too(can't think one where it doesn't). Clever code is useless code if it isn't also correct at the same time.












