Swapping two numbers

vegaseat 0 Tallied Votes 196 Views Share

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.

// 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 developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.