Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: All
Feb 22, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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.

Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date