Originally Posted by bitforce
An easy way to swap 2 variables without using another variable:
Easy way? I don't know, but sure it is inefficient (except if the optimizer is really good).
There *are* temporary variables if from an ISO standard point-of-view.
And, this algorithm can only be useful if (assuming an optimizer as good as Turbo C++ 1.0 optimizer or better, knowing that it is a very old compiler, with an obsolete optimizer):
- Both a and b are in a register (otherwise, I don't know any architecture where the temporary would be avoided)
- AND There is no builtin XCHG instruction at the assembly level (false for x86 and PowerPC)
- AND The CPU lacks register (in that case, it is very probable that the CPU has a XCHG instruction).
And, in that case, you may, ocasionally (rarely) gain little performance... In all other cases, you just can pray that the optimizer will understand your bad code, and implement it in a correct way.
Most compilers I know produce bad code for that.
If you use a 25 years old compiler, with a very very bad optimizer, it might also be possible that this compiler lacks register variables...
In that case, the following code:
Will produce something like (on x86-16, yep I can't imagine any such bad optimizer on x86-32):
mov ax, [bp-8] ; timings on a k6-2 CPU (1)
sub ax, [bp-4] ; 3
mov [bp-8],ax ; 4 CPU cycles
mov ax,[bp-4]
sub ax,[bp-8]
mob [bp-4],ax
mov ax, [bp-8]
sub ax, [bp-4]
mov [bp-8],ax ;11.5 CPU cycle (i.e. the last one might be paired with the next instruction)
Note : If the optimizer is even more bad than what I described, the generated code might even be worst.
And, your code (which has temporaries), on the same compiler might be twice as slow...
The classical
Will produce something like:
mov ax,[bp-4]
mov [bp-12],ax
mov ax,[bp-8]
mov [bp-4],ax
mov ax,[bp-12]
mov [bp-8],ax ; 5.5 CPU cycles (on a K6-2 CPU)
Note : I don't think that the compiler can generate worst code, even if there is no optimizer.
So, my point is that your code is *always* a bad idea.
This algorithm might only be used in some very special contexts, only on weird architectures (I don't know any such architecture, but it probably exists or existed), and at assembly level only!
Please, read my posts (SuperKoko) on these two threads (of another forum):
http://www.codeguru.com/forum/showthread.php?t=386883
http://www.codeguru.com/forum/showthread.php?t=383191
Also, remember that std::swap can be assumed as being optimal on your architecture : The compiler is allowed to do specific optimizations on it.