devxlogo

A Better Way to Swap Two Integer Variables

A Better Way to Swap Two Integer Variables

The algorithm shown in the tip, “Swap Values Using Only Two Variables” [“101 Tech Tips for VB Developers, Supplement to the February 1997 issue of VBPJ, page 25], crashes not only if (a+b) >= 32K, but if (a+b) < -32K also. I usually use this algorithm instead:

 a = a Xor b:	b = a Xor b:	a = a Xor b. 

This works for almost any programming language.

devx-admin

Share the Post: