References

In the Function Parameters lesson you learned that a function gets a copy of each argument. If the function changes its copy, the caller's variable does not change. Most of the time that is what you want. But sometimes the whole job of a function is to change the caller's variables, and return can send back only one value. For that, C++ has references.

A reference is a second name for a variable that already exists. To make one, write & after the type:

#include <iostream>
using namespace std;

int main() {
    int score = 50;
    int& other = score;
    other = 70;
    cout << score << "\n";
    return 0;
}

Output:

70

other is not a new variable with its own value. It is another name for score. Both names refer to the same place in memory, so setting other to 70 also sets score to 70.

A reference must be connected to a variable at the moment you create it. If you leave it empty, the program does not compile:

#include <iostream>
using namespace std;

int main() {
    int& other;
    return 0;
}

Output:

main.cpp: In function ‘int main()’:
main.cpp:5:10: error: ‘other’ declared as reference but not initialized

Pass by reference

References are most useful as function parameters. Here are two functions that look almost the same. Only the second one has &:

#include <iostream>
using namespace std;

void addBonusCopy(int score) {
    score += 10;
}

void addBonus(int& score) {
    score += 10;
}

int main() {
    int points = 50;
    addBonusCopy(points);
    cout << points << "\n";
    addBonus(points);
    cout << points << "\n";
    return 0;
}

Output:

50
60

addBonusCopy added 10 to its own copy, so points stayed 50. In addBonus, the parameter score is a reference. During the call, score is another name for points, so the += 10 changes points itself. This is called pass by reference.

pass by value:              pass by reference:
points     score            points
[ 50 ] --> [ 50 ]           [ 50 ] <-- score
           (a copy)         (the same variable)

Read without copying

Copying a long string takes time and memory. When a function only needs to read a value, you can pass a const reference:

void printTitle(const string& title) {
    cout << title << "\n";
}

No copy is made, and const means the function cannot change title. If it tries, the program does not compile. You will see const string& often in real C++ code.

In the exercise, a swap function gets copies and swaps nothing. Change its parameters to references so it swaps the caller's variables.