Swapping values in C++
Level 3131 keystrokes
swapNums takes both parameters by reference and swaps them through a temporary variable, so the caller's x and y are exchanged and "10 5" is printed. The standard library offers the same as std::swap.
C++ code
// Both parameters are references, so the changes reach the caller's variables1void swapNums(int& a, int& b) { // Saves a's value before it is overwritten2 int temp = a; // a gets b's value3 a = b; // b gets the saved old value of a4 b = temp;5}6 // Declares two ints in one statement7int x = 5, y = 10;8swapNums(x, y);// x and y have been swapped: prints 10 59cout << x << " " << y << endl;Output
10 5
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this C++ code and how often they appear.
<× 8;× 6=× 5,× 3"× 2(× 2)× 2&× 2{× 1}× 1