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.