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 copies1void swap(int& a, int& b) { // Save a's value before overwriting it2 int temp = a; // Writing to a and b changes the original variables3 a = b;4 b = temp;5}6 7int x = 10, y = 20;// Before the swap: prints 10 208cout << x << " " << y << endl;// x and y are passed by reference9swap(x, y);// After the swap: prints 20 1010cout << x << " " << y << endl;Output
10 20 20 10
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