C++ References
A reference is an alias — a second name for a variable that already exists. Anything you do to the reference you actually do to the original. References are created with & after the type.
Creating a reference
#include <iostream>
#include <string>
using namespace std;
int main() {
string meal = "pizza";
string& food = meal; // food is another name for meal
cout << meal << " " << food << "\n";
food = "pasta"; // changes meal too
cout << meal << " " << food << "\n";
}pizza pizza
pasta pasta
Two rules make references simple and safe:
- A reference must be initialised when it is declared:
int& r;does not compile. - A reference can never be re-seated. After
int& r = a;, the statementr = b;copies the value ofbintoa; it does not makerrefer tob.
Why references matter: passing to functions
By default C++ passes arguments by value — the function receives a copy. With a reference parameter, the function works directly on the caller's variable:
#include <iostream>
using namespace std;
void addBonusCopy(int points) {
points += 10; // changes only the local copy
}
void addBonus(int& points) {
points += 10; // changes the caller's variable
}
int main() {
int score = 50;
addBonusCopy(score);
cout << "after copy version: " << score << "\n";
addBonus(score);
cout << "after reference version: " << score << "\n";
}after copy version: 50
after reference version: 60
The classic example is a swap function, which is impossible to write with value parameters:
#include <iostream>
using namespace std;
void swapValues(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 1, y = 2;
swapValues(x, y);
cout << "x=" << x << " y=" << y << "\n";
}x=2 y=1
(The standard library already has std::swap in <utility>, which does exactly this.)
const references: fast and read-only
Copying a big object such as a long string or a vector with a million elements is expensive. A const reference avoids the copy and promises not to modify the argument. This is the most common parameter style in C++:
#include <iostream>
#include <string>
using namespace std;
int countChar(const string& text, char target) {
int n = 0;
for (char c : text) {
if (c == target) n++;
}
// text += "!"; // error: text is read-only
return n;
}
int main() {
string poem = "the rain in spain stays mainly in the plain";
cout << countChar(poem, 'a') << "\n";
cout << countChar("literal strings work too", 't') << "\n";
}5
3
A const reference can also bind to a temporary value such as a string literal, which a non-const reference cannot.
References in range-based loops
The same idea applies to loops. Without &, each element is copied into the loop variable; with & you can modify the elements in place:
#include <iostream>
using namespace std;
int main() {
int prices[] = {10, 20, 30};
for (int p : prices) p *= 2; // modifies copies only
for (int p : prices) cout << p << " ";
cout << "\n";
for (int& p : prices) p *= 2; // modifies the array
for (const int& p : prices) cout << p << " ";
cout << "\n";
}10 20 30
20 40 60
Parameter passing cheat sheet
| Parameter | Copies? | Can modify caller? | Use for |
|---|---|---|---|
T x |
yes | no | small types (int, double, char) |
T& x |
no | yes | output / in-out parameters |
const T& x |
no | no | large read-only inputs (string, vector) |
Warning: Never return a reference to a local variable from a function. The local is destroyed when the function ends, leaving a dangling reference.
Test yourself
Which declaration does NOT compile?
- int a = 1; int& r = a;
- int& r;
- const int& r = 5;
- int a = 1; const int& r = a;
Given int a = 1, b = 2; int& r = a; r = b;, what is a?
- 1
- 2
- Undefined
- Compile error
Which parameter type is best for reading a large std::string without copying it?
- string s
- string& s
- const string& s
- string* s