Swap without using extra variable (C++)

swapNoTemp.cpp

#include <iostream>

using namespace std;

/**
* Swap the parameters.
* @param a The first parameter.
* @param a The second parameter.
*/
void swap(int& a, int& b)
{
    int temp = a;
    a = b;
    b = temp;
}

/**
* Swap the parameters without a temp variable.
* Warning! Susceptible to overflow/underflow.
* @param a The first parameter.
* @param a The second parameter.
*/
void swapNoTemp(int& a, int& b)
{
    a -= b;
    b += a;// b gets the original value of a
    a = (b - a);// a gets the original value of b
}

int main() 
{
    int a = 100;
    int b = 500;
    cout << "a = " << a << " b = " << b << endl;
    swapNoTemp(a, b);
    cout << "a = " << a << " b = " << b << endl;
    return 0;
}

This code was developed by me, G. Samaras.

Notice, that I used as little C++ as possible, so that one can easy interchange between C and C++.
Have questions about this code? Comments? Did you find a bug? Let me know!😀
Page created by G. (George) Samaras (DIT)

9 thoughts on “Swap without using extra variable (C++)

  1. @Ronak
    Well, prone to overflow and underflow was not the proper phrase. We could say “susceptible to overflow/underflow”.
    The line of code that is the one to fear is this
    a -= b;
    We just need to find an overflow or underflow for this.
    And as a respected programmer said to me:
    “To do that, choose say, INT_MIN for a and INT_MAX for b (or some other suitable values in between). Of course, it might still be the case that it “works”, but you’re in the realm of implementation defined behaviour.”
    However, I decided to change the comment I have in the code, thank you very much for the comment🙂

  2. Maybe the safer way how to do this is to use XOR, but that approach is definitely the worst readable one:
    a = 2 = 0010; b = 6 = 0110
    a = XOR(a, b) // a = 4 = 0100
    b = XOR(a, b) // b = 2 = 0010
    a = XOR(a, b) // a = 6 = 0110
    but still it definitely should be over/underflow proof

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s