In the Pointers topic we used addresses to let a function change the caller's variables. It worked, but the code was full of & at the call site and * inside the function, and we always had to worry about null pointers. C++ adds a cleaner tool for most of these jobs: the reference.
A reference is simply another name for an existing object. Once you understand references, a lot of everyday C++ suddenly makes sense: why functions take const std::string&, why a range-based for loop is written for (auto& x : v), and how operators like [] can appear on the left side of =. In this chapter we cover lvalue references, const references, returning references, the dangers of dangling references, and a first look at rvalue references.
What is a Reference?
A reference is an alias: an alternative name for an object that already exists. It must be initialised when it is created, it always refers to the same object afterwards, and every use of the reference is a use of that object.
If your friend Rajesh is called "Raju" at home, there are not two people. Whatever you give Raju, Rajesh has. A reference works the same way.
Declaring and Using a Reference
A reference to an int has type int& (read: "reference to int"):
#include <iostream>
int main() {
int score = 40;
int& ref = score; // ref is another name for score
ref = 75; // changes score
std::cout << "score = " << score << ", ref = " << ref << '\n';
score += 5; // seen through ref too
std::cout << "score = " << score << ", ref = " << ref << '\n';
std::cout << std::boolalpha
<< "same address? " << (&ref == &score) << '\n';
}
Output:
score = 75, ref = 75
score = 80, ref = 80
same address? true
Notice what is missing compared with a pointer: no &score when creating it, no *ref when using it. ref is used exactly as if it were score, and &ref gives the address of score itself, because there is only one object.
int score = 40;
int& ref = score;
score, ref (two names, one object)
┌────────────┐
│ 75 │
└────────────┘
The Three Rules of References
A reference must be initialised. There is no such thing as an "empty" reference.
A reference cannot be re-seated. Once bound to an object, it refers to that object for its entire life.
A plain (non-const) reference must bind to a modifiable object that has a name or a location (an lvalue), not to a temporary value like
10ora + b.
Rules 1 and 3 are checked by the compiler:
int main() {
int& r1; // error: a reference must be initialised
int& r2 = 10; // error: non-const reference to a literal
const int& r3 = 10; // OK: const reference to a temporary
return r1 + r2 + r3;
}
r03_nocompile_rules.cpp: In function ‘int main()’:
r03_nocompile_rules.cpp:2:10: error: ‘r1’ declared as reference but not initialized
2 | int& r1; // error: a reference must be initialised
| ^~
r03_nocompile_rules.cpp:3:15: error: cannot bind non-const lvalue reference of type ‘int&’ to an rvalue of type ‘int’
3 | int& r2 = 10; // error: non-const reference to a literal
| ^~
Rule 2 is subtler, because assigning to a reference compiles fine. It just does not do what beginners expect:
#include <iostream>
int main() {
int a = 1, b = 2;
int& r = a; // r is bound to a, forever
r = b; // NOT "make r refer to b"
// it means a = b (copies the value 2)
b = 99;
std::cout << "a = " << a << ", b = " << b << ", r = " << r << '\n';
}
Output:
a = 2, b = 99, r = 2
r = b; copied the value of b into a (through r). r still refers to a, which is why changing b to 99 later does not affect r. There is no syntax at all for making a reference refer to a different object.
lvalues and rvalues, Briefly
Rule 3 uses two words you will meet constantly in C++:
An lvalue is an expression that refers to an object with an identity that lasts, typically something with a name:
x,arr[2],*p. You can take its address.An rvalue is a temporary value with no lasting identity:
10,a + b, the result of a function returning by value.
A plain int& is called an lvalue reference because it binds only to modifiable lvalues. That makes sense: int& r2 = 10; would let you write r2 = 20, "changing the number 10", which is meaningless.
Pass by Reference
The most common use of references is as function parameters. A reference parameter is bound to the caller's argument, so the function works directly on the original:
#include <iostream>
#include <string>
void swapRef(int& x, int& y) { // x and y ARE the caller's variables
int t = x;
x = y;
y = t;
}
void stats(const int arr[], int n, int& total, double& average) {
total = 0;
for (int i = 0; i < n; ++i) total += arr[i];
average = static_cast<double>(total) / n;
}
void addTitle(std::string& name) { // modifies the caller's string
name = "Dr. " + name;
}
int main() {
int a = 3, b = 7;
swapRef(a, b); // no & at the call site
std::cout << "a=" << a << " b=" << b << '\n';
int marks[] = {67, 92, 45, 88};
int sum;
double avg;
stats(marks, 4, sum, avg);
std::cout << "total=" << sum << " average=" << avg << '\n';
std::string person = "Meera";
addTitle(person);
std::cout << person << '\n';
}
Output:
a=7 b=3
total=292 average=73
Dr. Meera
Compare swapRef with swapByPointer from the Pointers topic: the same job, but no & when calling, no * inside, and no way to pass a null pointer by mistake. stats hands back two results through total and average, and addTitle changes the caller's string in place.
The C++ language now has three ways to pass an argument:
By value | By pointer | By reference | |
|---|---|---|---|
Function gets | A copy | A copy of the address | The original object |
Can change caller's variable? | No | Yes, through | Yes, directly |
Call looks like |
|
|
|
Can be "nothing"? | No | Yes, | No |
Cost for large objects | Copies the whole object | Cheap | Cheap |
One small downside: at the call site swapRef(a, b) looks exactly like a call by value, so a reader cannot tell that a and b may change without looking at the function. Good function names and const (next section) solve this in practice.
const References
Often we want to avoid copying a large object (a long string, a vector of a million numbers) but we do not want the function to change it. That is what const T& is for:
#include <iostream>
#include <string>
// Read-only access without copying the string.
std::size_t countVowels(const std::string& s) {
std::size_t count = 0;
for (char c : s) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') ++count;
}
// s += "x"; // would not compile: s is const
return count;
}
std::string makeGreeting() { return "good evening"; }
int main() {
std::string city = "bengaluru";
std::cout << countVowels(city) << '\n'; // binds to a variable
std::cout << countVowels("hyderabad") << '\n'; // binds to a temporary
const std::string& g = makeGreeting(); // temporary's life is extended
std::cout << g << " (" << g.size() << " chars)\n";
const double& d = 7; // a temporary double 7.0 is created
std::cout << d << '\n';
}
Output:
4
3
good evening (12 chars)
7
A const reference is special in two ways:
It promises read-only access. Inside
countVowels,s += "x"would not compile, so the caller knows the string is safe.It can bind to temporaries (rvalues).
countVowels("hyderabad")creates a temporarystd::stringfrom the literal, and the const reference binds to it. The temporary lives until the end of the full statement containing the call, which is long enough. A non-conststd::string¶meter would reject that call.
When a temporary is bound directly to a local const reference, as in const std::string& g = makeGreeting();, C++ extends the life of the temporary to match the reference. That is why g is still valid on the next line. The same happens in const double& d = 7;: a temporary double holding 7.0 is created and lives as long as d. This lifetime extension does not apply when a reference is returned from a function, or when a temporary is bound to a function parameter beyond the end of the call.
The everyday rule for function parameters:
Parameter type | Use when |
|---|---|
| Small, cheap-to-copy types: |
| Larger types the function only reads: |
| The function must modify the caller's object. |
| "No object" ( |
For read-only text specifically, std::string_view (C++17, see the Strings topic) is often an even better choice.
References in Range-based for Loops
We met for (int& m : marks) in the Arrays topic. Now we can explain it fully: the loop variable is declared for each element, and whether it is a copy or a reference decides what you can do.
#include <iostream>
#include <string>
int main() {
int marks[] = {50, 60, 70};
for (int m : marks) m += 5; // m is a copy: no effect
std::cout << marks[0] << ' ' << marks[1] << ' ' << marks[2] << '\n';
for (int& m : marks) m += 5; // m refers to each element
std::cout << marks[0] << ' ' << marks[1] << ' ' << marks[2] << '\n';
std::string names[] = {"Arjun", "Kavya", "Rohan"};
for (const std::string& n : names) { // no copy, read-only
std::cout << n << '(' << n.size() << ") ";
}
std::cout << '\n';
for (auto& n : names) n += "!"; // auto& deduces std::string&
std::cout << names[0] << ' ' << names[2] << '\n';
}
Output:
50 60 70
55 65 75
Arjun(5) Kavya(5) Rohan(5)
Arjun! Rohan!
Loop variable | What it is | Use it for |
|---|---|---|
| A copy of each element | Small types you only read, or when you want a private copy |
| A reference to each element | Modifying the elements |
| A read-only reference | Reading large elements (strings, objects) without copying |
Note that auto on its own always deduces a non-reference type: auto n = names[0]; is a copy. You must write the & yourself to get a reference.
Returning a Reference
A function can also return a reference. The call expression then is the referred object, so it can even appear on the left of =:
#include <iostream>
int& largest(int arr[], int n) { // returns a reference INTO the array
int best = 0;
for (int i = 1; i < n; ++i) {
if (arr[i] > arr[best]) best = i;
}
return arr[best];
}
int main() {
int stock[] = {12, 40, 7, 25};
largest(stock, 4) = 0; // assign to the returned element
for (int x : stock) std::cout << x << ' ';
std::cout << '\n';
int& top = largest(stock, 4); // now refers to stock[3]
top += 100;
std::cout << stock[3] << '\n';
int copy = largest(stock, 4); // copies the value; no reference kept
copy = -1; // changes only the copy
std::cout << copy << ' ' << stock[3] << '\n';
}
Output:
12 0 7 25
125
-1 125
largest(stock, 4) = 0;sets the largest element (40) to 0. This is exactly howv[i] = xworks forstd::vectorands[i] = 'X'forstd::string: theiroperator[]returns a reference (see the Operator Overloading topic).int& top = largest(...)keeps a reference, sotop += 100changedstock[3].int copy = largest(...)copies the value into a newint. Changingcopydoes not affect the array. Whether you get a reference or a copy depends on the variable you store the result in.
Never Return a Reference to a Local Variable
Returning a reference is safe only if the object outlives the function call: an array element passed in by the caller, a global, a member of an object that still exists. A local variable dies when the function returns:
int& badCounter() {
int count = 0;
++count;
return count; // count dies when the function returns
}
With -std=c++23, GCC rejects this:
r07_nocompile_return_local.cpp: In function ‘int& badCounter()’:
r07_nocompile_return_local.cpp:4:12: error: cannot bind non-const lvalue reference of type ‘int&’ to an rvalue of type ‘int’
4 | return count; // count dies when the function returns
| ^~~~~
The reason is a C++23 rule called simpler implicit move (proposal P2266): in a return statement, a local variable is treated as an rvalue, so it can no longer bind to a non-const int&. With -std=c++20 or earlier the same code compiles with only a warning ("reference to local variable 'count' returned"), and the caller receives a dangling reference. Whatever your standard, the code is wrong; return by value instead (int badCounter()).
Dangling References
A dangling reference refers to an object whose lifetime has ended. Using it is undefined behaviour, exactly like a dangling pointer.
A reference is not magic protection: it does not keep its object alive (apart from the temporary lifetime extension above). One very common trap involves std::vector, which stores its elements in one buffer and moves them to a bigger buffer when it runs out of room:
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {1, 2, 3};
v.shrink_to_fit(); // ask for no spare capacity (a non-binding request)
int& first = v[0];
std::cout << "first = " << first << '\n';
v.push_back(4); // needs a bigger buffer: elements move
std::cout << "first = " << first << '\n'; // dangling reference!
}
Built with g++ -std=c++23 -g -fsanitize=address,undefined. Output (trimmed; addresses differ on every run):
first = 1
=================================================================
==2591==ERROR: AddressSanitizer: heap-use-after-free on address 0x6d67755e0010 ...
READ of size 4 at 0x6d67755e0010 thread T0
#0 0x5732d570ea90 in main r08_asan_vector.cpp:11
...
freed by thread T0 here:
...
#9 0x5732d570e8e3 in main r08_asan_vector.cpp:10
Here the vector had room for exactly 3 elements (that is what g++ does for this code; shrink_to_fit itself guarantees nothing), so push_back(4) allocated a new buffer, moved the elements and freed the old one. first still refers into the freed buffer. Whenever a vector reallocates (which push_back, insert, resize or reserve do when the new size or requested capacity exceeds the current capacity), all references, pointers and iterators to its elements are invalidated. Even without reallocation, insert and erase invalidate those at or after the position they change. We will meet the full rules in the vector and Iterators topics; for now, do not hold a reference to a vector element while you add elements to that vector.
Pointers vs References
#include <iostream>
void incPtr(int* p) { if (p) ++*p; } // must handle "no object"
void incRef(int& r) { ++r; } // always has an object
int main() {
int x = 10;
incPtr(&x);
incPtr(nullptr); // allowed, function checks
incRef(x);
std::cout << x << '\n';
int* p = &x;
int& r = x;
std::cout << sizeof(p) << ' ' << sizeof(r) << '\n'; // sizeof(r) == sizeof(int)
int y = 0;
int*& rp = p; // reference to a pointer
rp = &y; // changes p itself
*p = 5;
std::cout << x << ' ' << y << '\n';
}
Output:
12
8 4
12 5
incPtrmust be ready fornullptr;incRefcannot be given "no object", so it needs no check.sizeof(r)gives the size of the referredint(4), not the size of an address. The standard does not even say whether a reference occupies storage; in practice compilers usually implement a reference that must be stored (for example, a reference parameter) as an address, but you cannot observe or change that address.int*& rp = p;is a reference to a pointer (read right to left: rp is a reference to an int pointer). Assigning torpchangespitself, which is the reference version of theint**trick from the Pointers topic.
Feature | Pointer | Reference |
|---|---|---|
Must be initialised | No (but should be) | Yes |
Can be null | Yes | No (a valid program has no null references) |
Can be re-pointed | Yes | No |
Access syntax |
| Same as the object: |
Arithmetic | Yes ( | No |
| Size of an address | Size of the referred type |
Pointer/reference to it |
| No reference to reference, no pointer to reference |
Arrays of them |
| Not allowed |
Typical use | Optional objects, arrays, C APIs, data structures | Parameters, return values, aliases |
A simple guideline: use a reference when there is always an object; use a pointer when "no object" is possible or when you need to re-point.
A First Look at Rvalue References (C++11)
C++11 added a second kind of reference, written T&&, which binds only to rvalues (temporaries). Overloading on the kind of reference lets a function tell a named object apart from a temporary:
#include <iostream>
#include <string>
void take(std::string&) { std::cout << "lvalue reference version\n"; }
void take(const std::string&) { std::cout << "const lvalue reference version\n"; }
void take(std::string&&) { std::cout << "rvalue reference version\n"; }
int main() {
std::string s = "hi";
const std::string cs = "hello";
take(s); // a named, modifiable object
take(cs); // a const object
take(std::string("tmp")); // a temporary
take(s + "!"); // the result of + is a temporary too
int&& rr = 5; // binds to a temporary
rr += 1; // and can modify it
std::cout << rr << '\n';
}
Output:
lvalue reference version
const lvalue reference version
rvalue reference version
rvalue reference version
6
Why would a function care? A temporary is about to die anyway, so a function that receives it may safely steal its contents (for example, take over a string's buffer) instead of copying them. That idea, move semantics, is one of the most important features of modern C++, and it has its own topic: Move Semantics & Rvalue References. For now, just remember the binding rules:
Reference type | Binds to lvalues? | Binds to rvalues (temporaries)? |
|---|---|---|
| Yes (non-const ones) | No |
| Yes | Yes |
| No | Yes |
Common Mistakes
Thinking
r = b;re-seats a reference. It assignsb's value to the referred object.Forgetting the
&in a parameter or loop variable (for (auto x : v)) and then wondering why changes are lost.Passing large objects by value (
void print(std::string s)) whenconst std::string&would avoid the copy.Taking
T&whenconst T&is enough, which needlessly rejects temporaries and const objects.Returning a reference to a local variable or to a temporary.
Keeping a reference to a container element while adding elements to the container.
Writing
int& a, b;: as with pointers, the&belongs toaonly, andbis a plain int.
Interview and GATE Questions
What is the output of this program?
#include <iostream>
void f(int a, int& b, int* c) {
a = a + 10;
b = b + 10;
*c = *c + 10;
c = &b;
*c = *c + 1;
}
int main() {
int x = 1, y = 2, z = 3;
f(x, y, &z);
std::cout << x << ' ' << y << ' ' << z << '\n';
int p = 5;
int& q = p;
int& t = q;
t = 8;
q++;
std::cout << p << '\n';
}
1 13 13
9
a is a copy, so x stays 1. b is y, so y becomes 12. *c is z, so z becomes 13. Then c = &b re-points the local copy of the pointer to y (the caller's pointer is unaffected), and *c + 1 makes y 13. In the second part, q and t are both names for p (a reference initialised from a reference refers to the same object), so t = 8 and q++ give 9.
Can a reference be null? Can it be re-seated?
No to both. A reference must be bound to a valid object when it is created and stays bound to it. Code such as int& r = *p; with a null p already has undefined behaviour at the dereference, so a correct program never contains a "null reference".
Why can const int& r = 10; compile but int& r = 10; cannot?
A non-const lvalue reference may only bind to a modifiable lvalue, and 10 is an rvalue. A const reference is allowed to bind to rvalues: the compiler creates a temporary int holding 10, binds r to it, and extends the temporary's lifetime to that of r.
Why are function parameters often written as const std::string&?
It avoids copying the string (cheap for any length), guarantees the function will not modify it, and still accepts temporaries such as string literals or a + b. For pure read-only text, std::string_view (C++17) is an alternative.
What does sizeof return for a reference?
The size of the referred type. For double& r = d;, sizeof(r) equals sizeof(double), usually 8.
Is returning a reference from a function ever safe? Give an example.
Yes, when the referred object outlives the call: an element of an array or container passed in by the caller, a global or static variable, or a member of an object that still exists (like std::vector::operator[], which returns a reference to an element). Returning a reference to a local variable is always wrong.
Can you have an array of references?
No. Arrays of references, pointers to references and references to references are not allowed. You can have a reference to an array, for example int (&r)[5] = arr;, which, unlike a pointer, keeps the size: sizeof(r) is 5 * sizeof(int).
In Simple Words
A reference is another name for an existing object. It must be initialised, can never be null, and can never be made to refer to something else.
Use
T¶meters to modify the caller's object,const T&to read large objects without copying.const T&can bind to temporaries; a plainT&cannot.Use
auto&/const auto&in range-based for loops to avoid copies or to modify elements.Returning a reference is fine only if the object outlives the function; never return a reference to a local.
A reference does not keep its object alive: watch out for dangling references, especially into containers that grow.
T&&(C++11) binds to temporaries and is the basis of move semantics.