Reference parameters in C++

Level 4155 keystrokes

A swap function takes two int references, so it exchanges the caller's variables: 10 20 becomes 20 10.

C++ code

// a and b are references: they are aliases for the caller's variables, not copies
1void swap(int& a, int& b) {
// Save a's value before overwriting it
2 int temp = a;
// Writing to a and b changes the original variables
3 a = b;
4 b = temp;
5}
6
7int x = 10, y = 20;
// Before the swap: prints 10 20
8cout << x << " " << y << endl;
// x and y are passed by reference
9swap(x, y);
// After the swap: prints 20 10
10cout << x << " " << y << endl;

Output

10 20
20 10
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.

  • <× 16
  • ;× 7
  • =× 5
  • "× 4
  • ,× 3
  • (× 2
  • )× 2
  • &× 2
  • {× 1
  • }× 1

More C++ examples at level 4

← C++ typing practice