eHow launches Android app: Get the best of eHow on the go.

How To

How to Switch the Values of Two Variables Without Using a Temporary Variable

Member
By Adam Wolkov
User-Submitted Article
(6 Ratings)

In programming, there are many times that you need to switch two variable values (such as in a Bubble Sort). Most people would show you how to do it with three variables and use wasteful operations, but I can show you how to do it with two...EFFICIENTLY!

Difficulty: Easy
Instructions

Things You'll Need:

  • A basic understanding of binary numbers
  • To know how XOR works
  1. Step 1
     

    Understanding XOR:

    XOR or Exclusive-Or, is similar to the commonly used INCLUSIVE-Or, except that if both inputs are 1, the output is 0 (as opposed to INCLUSIVE-Or where the value is 1).


    This addresses this case where we normally do something like:

    int ii1 = 1;
    int ii2 = 2;
    int tmp;

    tmp = ii1;
    ii1 = ii2;
    ii2 = tmp;

  2. Step 2

    Now, the magic:

    A triple XOR performed on two variables will SWITCH THEM!!!

    So, in C#:

    int ii1 = 1;
    int ii2 = 2;

    ii1 ^= ii2;
    ii2 ^= ii1;
    ii1 ^= ii2;


    The variables have now been swapped without using a temporary variable!

Tips & Warnings
  • Binary operations are usually VERY efficient.
  • Be sure to perform your xor operations in the correct order.
  • The ^ (circumflex or caret) is commonly the XOR operation, but check to make sure what it is in the programming language that you use (^ in C++, C#, Java and PHP, xor in Pascal, Xor in VB.NET, etc)

Comments  

pixiemama said

Flag This Comment

on 10/9/2008 5*

raystarck said

Flag This Comment

on 6/24/2008 Nice article! keep posting

MARCUS said

Flag This Comment

on 11/13/2007 THIS ARTICLE IS AMAZING!!!!

Subscribe

Post a Comment

Post a Comment

Related Ads

  • Have you done this? Click here to let us know.
I Did This
Tags
Get Free Internet Newsletters

Copyright © 1999-2009 eHow, Inc. Use of this web site constitutes acceptance of the eHow Terms of Use and Privacy Policy.   en-US Portions of this page are modifications based on work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License.

Demand Media
eHow_eHow Technology and Electronics