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.

161 Views
``````// 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;
}``````

Scientist

## FireSBurnsmuP

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

## Duoas 1,025

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.