C++ How To Swap Two Variables
Swap Two Variables
Swap the values of two variables by using a third, temporary variable:
Example
int a = 5;
int b = 10;
int temp = a;
a = b;
b = temp;
cout << "a = " << a << "\n";
cout << "b = " << b;
Explanation:
First, temp keeps a copy of a.
Then a gets the value of b, and b gets the old value of a from temp.
Tip: C++ also has a built-in swap() function that does the same: swap(a, b);