Swapping two numbers

vegaseat

This question came up on the forum. How do you swap two numbers without using a temporary variable? I used all the power of my brain to solve this at four o'clock in the morning. In all fairness, swapping two numbers using a temporay variable is about five times faster. This code is just for the curious.

172 Views
About the Author

Scientist

// swap two numbers without using a temporary variable
// the numbers can be either integers or floats

#include <iostream>

using namespace std;

int main()
{
    float a = 1.7;
    float b = -7.1;
    
    cout << "a = " << a << "   b = " << b << endl; 
    // swap a with b
    a = a + b;
    b = a - b;
    a = a - b;
    cout << "after swapping a with b:" << endl;
    cout << "a = " << a << "   b = " << b << endl; 
    
    cin.get();   // wait
    return EXIT_SUCCESS;
}
FireSBurnsmuP 0 Posting Whiz in Training

Quite clever! I am not sure I would have thought of that one.
Thanks for submitting that, I feel enlightened now.

Duoas 1,025 Postaholic Featured Poster

Nice. The only problem is that you can have overflow, which would destroy the values of the variables. Use bitwise operations instead:

a ^= b;
b ^= a;
a ^= b;

Enjoy.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.