Variable Swap

Actionscript:
  1. //
  2. // swap some variables
  3. // all techniques except the first are from http://cpptruths.blogspot.com/2006/04/swapping-two-integers-in-one-liner.html
  4. //
  5. var a:Number = 1.1;
  6. var b:Number= 2.2;
  7.  
  8. trace(a, b);
  9.  
  10. // best, fastest, easiest to read way
  11. var t:Number= a;
  12. a = b;
  13. b = t;
  14.  
  15. trace(a, b);
  16.  
  17. // not recommended slower ways:
  18.  
  19. b=a+b-(a=b);
  20.  
  21. trace(a, b);
  22.  
  23. // xor versions will only work with ints and uints
  24. trace("\nxor kills decimals:");
  25.  
  26. // easy to understand xor version
  27. a^=b;
  28. b^=a;
  29. a^=b;
  30.  
  31. trace(a, b);
  32.  
  33. // one line xor version
  34.  
  35. a=(b=(a=b^a)^b)^a;
  36.  
  37. trace(a, b);
  38.  
  39. /* outputs:
  40. 1.1 2.2
  41. 2.2 1.1
  42. 1.1 2.2
  43.  
  44. xor kills decimals:
  45. 2 1
  46. 1 2
  47. */

The above swaps variables a and b in a few different ways. The first way (using a temp variable) is the best and fastest way... the rest of the ways are just interesting and fun.

I was coding and something reminded me that there are obscure variable swapping techniques out there... so I figured I'd google for a bit.... there are tons of examples of these online - with lots of good explanations.... I got the above from this link.

This entry was posted in Operators, one-liners, variables and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*