Skip to content

Instantly share code, notes, and snippets.

@eligundry
Created October 4, 2011 02:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eligundry/1260773 to your computer and use it in GitHub Desktop.
Save eligundry/1260773 to your computer and use it in GitHub Desktop.
Number Swapper
#include <iostream>
using namespace std;
/*
* Basically, this code right here will swap the
* values of two variables. I was able to do it
* in one line, which my professor said should be
* impossible.
*/
int main()
{
double a, b;
cout << "Let's swap two numbers, a & b" << endl;
cout << "a = ";
cin >> a;
cout << "b = ";
cin >> b;
// Swap
cout << "Swap!" << endl;
/*
* This how Nick showed us to do it.
* b += a;
* a = b - a;
* b -= a;
*/
/*
* This is my way, in two lines, note the comma
* b += a;
* b -= a = b - a;
*/
// And here's my one line solution
// b -= ((b += a), a = b - a);
// And here's Stephen Walentik's awesome solution
b = (a + b) - (a = b);
cout << "a == " << a << endl;
cout << "b == " << b << endl;
return 0;
}
@ntietz
Copy link

ntietz commented Oct 4, 2011

I really like this: b = (a + b) - (a = b);
I think that's clever.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment