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 variables
1void swapNums(int& a, int& b) {
// Saves a's value before it is overwritten
2 int temp = a;
// a gets b's value
3 a = b;
// b gets the saved old value of a
4 b = temp;
5}
6
// Declares two ints in one statement
7int x = 5, y = 10;
8swapNums(x, y);
// x and y have been swapped: prints 10 5
9cout << x << " " << y << endl;

Output

10 5
Practice typing this code

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

More C++ examples at level 3

← C++ typing practice