Swapping Two Variables Without Using a Temporary

Swapping Two Variables Without Using a Temporary

The classic implementation of the swap algorithm looks like this:

   void swap (int & i, int & j)  {    int temp = i;    i = j;    j = temp;  }

Is it possible to swap i and j without using a third variable? Yes it is:

   swap(int & i, int & j)  {    i -= j;    j += i; // j gets the original value of i    i = (j - i); // i gets the original value of j  }

However, this version isn’t more efficient than the previous one (in fact, it’s probably less efficient) because the compiler must generate a temporary variable to evaluate the following expression:

   i = (j - i); 

Although it has no practical value, this exercise may show up in your next job interview so it’s worth remembering how to solve it.

See also  Small Business Strategies with Venmo

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist