Skip to content

Instantly share code, notes, and snippets.

@asa55
Created April 3, 2020 22:38
Show Gist options
  • Save asa55/78496df8daee8e694e4837f8ce67b4b1 to your computer and use it in GitHub Desktop.
Save asa55/78496df8daee8e694e4837f8ce67b4b1 to your computer and use it in GitHub Desktop.
// how to swap two numbers without using a temporary variable
// think about it this way
// x <-- a
// y <-- b
// x' <-- x - y = a - b
// y' <-- x' + y = ( a - b ) + b = a
// x''<-- y' - x' = a - ( a - b ) = b
#include <iostream>
int x = 5, y = 10;
void swap(int& _x, int& _y)
{
_x = _x - _y;
_y = _x + _y;
_x = _y - _x;
}
int main ()
{
std::cout << "x: " << x << " " << "y: " << y << std::endl;
swap(x, y);
std::cout << "x: " << x << " " << "y: " << y << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment