Declaring references
- C++ course
- Beginner
- Lesson 72/116
- 5 min
Learn to declare references with &.
Declaring references
A reference is declared with the & sign: int& r = x;. Here & means 'I want a reference here'. The reference must be bound to a variable at declaration; it cannot be left empty.
After binding, r and x are the same thing. Writing std::cout << r; shows the value of x. The spacing between the type and & does not matter; int& r and int &r are equivalent.
Binding and constancy
A reference is bound to a variable at declaration and this binding stays fixed for its whole life. That is, after int& r = x;, writing r = y; does not re-bind r to y; instead, the value of y is copied into x.
This behavior can be surprising at first. Do not think of a reference as 'redirecting to another variable'; it is bound once and stays with the same target. For re-binding, you need a pointer.
Practice Print the reference
Declare int x = 42;. Bind a reference with int& r = x;. Print r with std::cout.
Starter code
#include <iostream>
int main() {
// Declare x
// Bind r as a reference to x
// Print r
return 0;
}Sample solution
#include <iostream>
int main() {
int x = 42;
int& r = x;
std::cout << r << "\n";
return 0;
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does this code print?
int x = 10;
int& r = x;
r = 20;
std::cout << x;- 20 Correct answer
- 10
- 0
- Error
Explanation: The assignment r = 20 also makes x become 20, because r is an alias for x.
2 Print the reference
std::cout << ____;
std::cout << r;
Explanation: std::cout << r; prints the value of x.
3 Match each expression to its meaning
| Term | Meaning |
|---|---|
int& r = x |
Binding |
r |
Alias for x |
x |
Original variable |
42 |
Value |