C++ References
What is a Reference?
In C++, a reference is an alias for an existing variable. A reference variable provides an alternative name for the original variable, allowing it to be accessed and modified through that name. Unlike pointers, references cannot be reassigned, and they must be initialized when they are declared.
How to Declare and Initialize a Reference
To declare a reference, you need to use the ampersand (&) symbol followed by the reference variable name. The reference variable must be initialized with an existing variable at the time of declaration.
Example:
int num = 42;
int& numRef = num;
In this example, 'numRef' is a reference to the variable 'num'. Any changes made to 'numRef' will also affect 'num'.
How to Use a Reference
Once a reference has been initialized, you can use it just like the original variable. Here is an example demonstrating how to use a reference:
Example:
int num = 42;
int& numRef = num;
numRef = 10; // This will change the value of 'num' to 10
In this example, 'numRef' is used to modify the value of 'num'. The value of 'num' becomes 10 after the assignment.
Passing References to Functions
One common use case for references is passing them as arguments to functions. This allows the function to modify the original variable passed as an argument, rather than working
Example:
void increment(int& num) {
num++;
}
int main() {
int value = 5;
increment(value);
// The value of 'value' is now 6
}
In this example, the 'increment()' function takes a reference to an integer as its parameter. When the 'value' variable is passed to the function, the function modifies the original variable directly, increasing its value by 1.
Limitations of References
While references can be quite useful in certain situations, they also have some limitations: