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

By Adam Wolkov

Rate: (3 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!

Instructions

Difficulty: Easy

Things You’ll Need:

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

Step1
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;
Step2
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

| View All Comments

MARCUS said

Flag This Comment

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

View All

Post a Comment

POST A COMMENT

Request a New How-To Article

Looking for more How To information? Chances are there’s an eHow member who knows how to do what you’re looking to do. Submit an article request now!

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

eHow Member: Adam Wolkov

Adam Wolkov

Enthusiast Enthusiast | 650 Points

Category: Internet

Articles: See my other articles

Related Ads

Internet

Veesites
Meet Virginia DeBolt eHow’s Internet Expert.