0

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;
}
3
Contributors
2
Replies
7
Views
12 Years
Discussion Span
Last Post by Duoas
0

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

1

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.

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.