References

“References” can be thought of as “easier pointers.” Rather than representing the memory address of a variable, they represent the variable itself. Let’s see how references can work just like pointers in our addFive function from earlier:

#include <iostream>

void addFive(int &numberReference) {
    numberReference += 5;
}

int main() {
    int number = 4;
    std::cout << "Number before adding 5: " << number << "\n";
    addFive(number);
    std::cout << "Number after adding 5: " << number << "\n";
    return 0;
}

Program output:

Number before adding 5: 4
Number after adding 5: 9

Rather than first taking the address of number and then dereferencing numberPointer in the addFive function, we simply pass a “reference” of the number variable to the addFive function. In C++, references are indicated by an ampersand between the data type and name of the reference variable. Just like the asterisk, the ampersand is used for two completely different tasks…

You can see that passing variables “by reference” behaves just like passing variables by pointer. In this case, rather than a copy of the number variable being passed to the addFive function, a reference of that variable (the variable itself) is passed, allowing the addfive function to modify it.

If a variable’s value is changed, any references of it are also changed. If any references of a variable are changed, the variable is also changed.

Because of how references work, they can also improve the efficiency of programs just like how pointers can. By passing a variable by reference to a function, a copy of that variable is never made. Therefore, memory space can also be saved.