Understanding References in C++
References are an important advantage of using C++. If making your code clean, fast and low on memory is meaningful to you, understanding references is necessary.
What is references?
- A reference makes it possible to call a variable by using an extra name in C++.
- Unlike a pointer, a reference can’t be made null and must be set from the moment it is declared.
- As long as the program keeps running, the system will keep the reference to the variable. Right after initialization, the reference does the same job as the variable.
- Modifications to a variable introduced by a reference variable will be shown in the original variable.
- Changes you make to a reference in a function are updated in the main variable you passed in.
Syntax:
int a = 10;
int &r = a;
Now, both a and r refer to the same memory location
Example:
#include
using namespace std;
int main() {
int a = 13;
int &b = a;
cout << “a: ” << a << “, b: ” << b << endl;
y = 24; // changing y also changes
cout << “a: ” << a << “, b: ” << b << endl;
return 0;
}
Output:
a: 13, b: 13
a: 24, b: 24
Differences between References and pointers in C++:
| Feature | Reference | Pointer |
| Initialization | Must be initialized | Can be uninitialized |
| Reassignment | Not allowed | Allowed |
| Null values | Not allowed | Allowed |
| Syntax | Int &b = a; | Int * ptr = &a; |
| Memory address | No direct access | Direct access allowed |
| Dereferencing | Automatic | Manual |
When to use references:
- passing variables to functions without copying.
- When we want a safer and clearer syntax.
References in Function Arguments:
Commonly reference is used for passing arguments in a function
- To Avoid copying large objects.
- For Modify the original value.
Example: Pass by Reference
void Swap(int &s, int &m) {
int temp = s;
s = m;
m = temp;
}
int main(){
int c = 10, d = 20;
Swap(c, d);
return 0;
}
Returning by Reference:
Functions can also return references, allowing direct access to internal variables or allowing chaining.
Example:
int& show(int ar[], int ind) {
return ar[ind]; // returning reference
}
Int main(){
int num[4] = {1, 2, 3, 4};
show(num, 2) = 13; // directly modifies array
return 0;
}
Common Mistakes to Avoid:
1.Dangling References:
Returning reference to a local variable causes undefined behavior.
int& fun() {
int y = 12;
return x; // x will get destroyed
}
2.Uninitialized References:
Every reference must be initialized when declared.
int &ref; // reference must be initialized
Conclusion: