Number Swapper

16.1 Number Swapper: Write a function to swap a number in place (that is, without temporary variables).

  • Notes:

    • Math is fun!

// extra space
void swap(int *a, int *b) {
    int temp = *(a);
    *(a) = *(b);
    *(b) = temp;
}

// not safe
void swap2(int *a, int *b) {
    *(a + 1) = *(b);
    *(b) = *(a);
    *(a) = *(a + 1);
}

// safe and inplace
void swap3(int *a, int *b) {
    *(a) = *(a)+*(b);
    *(b) = *(a)-*(b);
    *(a) = *(a)-*(b);
}

int main() 
{
    int a, b;
    a = 1; b = 2;
    swap(&a, &b);
    cout << a << " " << b << endl;

    //swap2(&a, &b);
    //cout << a << " " << b << endl;

    a = -1; b = 2;
    swap3(&a, &b);
    cout << a << " " << b << endl;

}

Last updated