C++ References
In C++, a reference is an alias for another variable. Once a reference is initialized with a variable, it can be used interchangeably with that variable. References are commonly used for function arguments to avoid copying large data and to allow modifications to the original variable.
Syntax
data_type &reference_name = variable_name;
Where:
- References must be initialized when declared.
- References cannot be made to null or reassigned to reference another variable.
- Passing by reference allows functions to modify the original variable and avoids copying large data.
Next Topic
Next, learn about C++ Classes and Objects.
- data_type – Type of the variable being referenced.
- &reference_name – Declares a reference using the ampersand
&.
Example: Basic Reference
#include <iostream>
using namespace std;
int main() {
int num = 10;
int &ref = num; // Reference to num
cout << "Original num: " << num << endl;
cout << "Reference ref: " << ref << endl;
// Modifying value through reference
ref = 20;
cout << "Modified num: " << num << endl;
return 0;
}
Output
Original num: 10 Reference ref: 10 Modified num: 20
Example: Reference as Function Parameter
#include <iostream>
using namespace std;
// Function to double a number using reference
void doubleValue(int &x) {
x = x * 2;
}
int main() {
int num = 15;
cout << "Before: " << num << endl;
doubleValue(num); // Pass by reference
cout << "After: " << num << endl;
return 0;
}
Output
Before: 15 After: 30
Important Notes
- References must be initialized when declared.
- References cannot be made to null or reassigned to reference another variable.
- Passing by reference allows functions to modify the original variable and avoids copying large data.
Next Topic
Next, learn about C++ Classes and Objects.