Stage 5: References and References as Function Parameters
Understanding the reference mechanism in C++: how variable aliases work and why they are key to efficient argument passing.
References in C++: A Programmer's Power Tool
A reference is essentially an alias or a "second name" for an already existing variable. Unlike pointers (which store an address), a reference behaves exactly like the variable it refers to, but it does not create a copy in memory. For your exam, this is the absolute foundation of efficient programming.
1. Basic Syntax and Rules
We declare a reference using the & operator placed next to the data type.
int original = 10;
int &ref = original; // ref is now an alias for original
ref = 20; // Changes the value of original to 20
std::cout << original; // Prints 20Golden Rules of References:
- Must be initialized: You cannot write
int &ref;without assigning it to a variable. - Cannot be "null": A reference must always point to a valid object (there is no equivalent to
nullptr). - Non-reseatable: Once assigned, a reference points to the same variable for the rest of its life. You cannot "switch" it to another object.
2. Reference as a Function Parameter
This is the most important use of references in exams. Passing by reference solves two main problems:
A. Performance (No Copying)
If you pass a large object to a function (e.g., a long std::string or a large structure), passing by value forces the computer to make a copy of the entire object. A reference only sends "access" to the original.
B. Modifying Arguments
By default, functions operate on copies. If you want a function to change a variable declared in main, you must use a reference.
void addVat(double &price) {
price *= 1.23;
}
int main() {
double product = 100.0;
addVat(product);
// product is now 123.0
}3. Reference to Constant (const &)
Often we want to benefit from the efficiency of references (no copying) while simultaneously guaranteeing that the function will not modify our variable. In such cases, we use const.
void displayLargeText(const std::string &text) {
// text[0] = 'A'; // COMPILE ERROR - cannot modify const
std::cout << text;
}Exam Tip: If a function only needs to "read" data from a large object, always use const &.
4. Comparison: Value vs. Reference
| Feature | By Value | By Reference (&) |
|---|---|---|
| Copy | Yes, a new variable is created | No, it's just an alias |
| Original Modification | No | Yes |
| Speed | Slower for large data | Always fast |
| Call Syntax | func(x) | func(x) (identical) |
Common Exam Mistakes
-
Returning a reference to a local variable: This is a critical error. A local variable disappears after the function finishes, so a reference to it would lead to nothing (dangling reference).
cppint& bad() { int x = 10; return x; // ERROR! x will cease to exist } -
Confusing
&in declaration with&as address-of operator:int &r = x;(reference declaration)cout << &x;(getting the memory address - this is different!)
-
Missing
&in for-loops: When operating on arrays of objects, usingfor (auto &element : array)prevents unnecessary copying of each element during every iteration.
You might also like
Dynamic Memory Allocation in C++: Building and Demolishing in RAM
Understand the new and delete operators. We explain the difference between the stack and the heap, how to manage memory, and avoid memory leaks.
C++ Pointers: Address-of and Dereference Operators for Everyone
Scared of pointers? Don't be! In this step-by-step guide, we explain memory addresses, the & operator, and the * asterisk.
Stage 11: Pointer Arithmetic in C++
Understanding how C++ operates on memory addresses. Learn why ptr++ is more than just adding one.