Created
October 4, 2011 02:29
-
-
Save eligundry/1260773 to your computer and use it in GitHub Desktop.
Number Swapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I really like this: b = (a + b) - (a = b);
I think that's clever.