Search code examples
c++functionimplementationeffective-c++

swap implementations: efficiency & range of applicability?


I'm trying to cover all swapfunction implementations.

In the following implementations of the swap function there is no need of temporary variable to interchange the values of the two parameters:

void swapNoTemp1(int &a, int &b){
    a = a + b;
    b = a - b;
    a = a - b; 
}

or

template <class T>
void swapNoTemp2(T& i, T& j){
    i -= j;
    j += i;  
    i = (j - i);  
}

or

void swapNoTemp3(int &a, int &b){
    a ^= b;
    b ^= a;
    a ^= b;
}

thus making it more effective, in terms of used memory, than:

void swap(int &a, int &b){
    int temp = a;
    a = b;
    b = temp; 
}

On the other hand, swap could be implemented using:

void swapPointers(int *i, int *j) {
    int t = *i;
    *i = *j;
    *j = t;
}

I'am trying to compare all existing implementations and understand their range of applicability.


Solution

  • The behavior of the first function is undefined. The arithmetics may lead to overflow, and on some machines, overflows lead to exceptions.

    The standard states:

    If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined. [ Note: most existing implementations of C++ ignore integer overflows. ... ]

    Although in practice you have good chances that the function will work, it is perhaps better to avoid it.