![]() |
VOOZH | about |
References in C++ provide a way to create an alternative name for an existing variable. They allow programmers to access and modify the original variable directly without creating a separate copy, making programs more efficient and easier to read.
10 22
Explanation: In this program, ref is a reference to the variable x, meaning ref is just another name for x. When the value of ref is modified, it directly changes the value of x, since both ref and x refer to the same memory location.
If you've worked with pointers before, references may seem similar because both refer to the same memory location. However, references provide a simpler and more readable way to access an existing variable without using *.
The & symbol is used to declare a reference.
T &ref = var;
Parameters
Here, ref becomes an alias for the variable var.
Important Points About References
References are widely used in C++ to avoid unnecessary copying and to provide direct access to existing objects. Some common applications are discussed below.
References are commonly used in function arguments to allow modification of the original variable passed to the function. They are also more efficient for large data structures since no copies are made.
20
Explanation: The parameter x is a reference to a. Therefore, any modification made to x inside modifyValue() directly changes the value of a. No additional copy of the variable is created.
Functions in C++ can return references to variables. This allows the returned value to be accessed or modified directly without creating a copy, making it useful for improving performance and enabling direct updates to existing objects.
x = 10, y = 30
Explanation: The function getMax() returns a reference to the larger of the two variables. Since maxVal is a reference, assigning 30 to it directly modifies the original variable (y in this case). The output becomes x = 10, y = 30.
Note: Never return a reference to a local variable because local variables are destroyed when the function returns, leaving the reference dangling.
Range-based for loops normally iterate over elements by value. By using references, you can modify the original elements stored in the container directly.
15 25 35 45
Explanation: The loop variable x is declared as a reference (int&). Therefore, any modification made to x directly updates the corresponding element in the vector. Each element is increased by 5.
Although references are convenient and safe to use, they have some limitations:
References provide several benefits over pointers in many situations:
For a detailed comparison between references and pointers, refer to Pointers vs References.