Cpp Function Call By Reference
## C++ Call by Reference
In C++, **Call by Reference** is a method of passing arguments to a function where the formal parameters of the function act as aliases for the actual arguments passed during the call.
Unlike *Call by Value* (which creates a copy of the data), passing arguments by reference copies the address of the argument into the formal parameter. Inside the function, this reference is used to access the actual argument. This means that any modifications made to the parameter inside the function directly affect the original variable.
---
## Syntax and Mechanism
To declare a parameter as a reference, you append the ampersand (`&`) symbol to the data type in the function signature.
```cpp
void functionName(DataType ¶meterName) {
// Function body
}
```
### Key Characteristics:
* **No Copying:** The function does not allocate new memory for the argument's value; it operates directly on the existing memory location of the passed variable.
* **Direct Modification:** Any changes made to the parameter inside the function are instantly reflected in the caller's scope.
* **Clean Syntax:** Unlike pointers, you do not need to dereference the variable (using `*`) inside the function, nor do you need to pass the address (using `&`) when calling the function.
---
## Code Example: Swapping Two Numbers
The classic use case for Call by Reference is a swap function. Below is a complete C++ program demonstrating how to swap the values of two integer variables using references.
```cpp
#include
using namespace std;
// Function declaration (prototype)
void swap(int &x, int &y);
int main() {
// Local variable declarations
int a = 100;
int b = 200;
cout << "Before swap, value of a: " << a << endl;
cout << "Before swap, value of b: " << b << endl;
/* Call the function to swap the values */
swap(a, b);
cout << "After swap, value of a: " << a << endl;
cout << "After swap, value of b: " << b << endl;
return 0;
}
// Function definition
void swap(int &x, int &y) {
int temp;
temp = x; /* Save the value at address x */
x = y; /* Put y into x */
y = temp; /* Put temp (original x) into y */
}
```
### Output:
```text
Before swap, value of a: 100
Before swap, value of b: 200
After swap, value of a: 200
After swap, value of b: 100
```
---
## Key Benefits of Call by Reference
1. **Modifying Caller Variables:** It allows a function to modify one or more variables in the calling environment. This is highly useful when a function needs to "return" multiple values.
2. **Zero Copy Overhead:** When passing large objects (such as custom classes, structures, or `std::vector`), copying them can be computationally expensive. Passing by reference avoids this overhead, significantly improving performance.
3. **Cleaner Syntax than Pointers:** References provide the same performance benefits as pointers but with a cleaner, safer, and more readable syntax. You do not have to deal with pointer arithmetic or null-pointer checks.
---
## Common Use Cases
### 1. Modifying External Variables
As demonstrated in the `swap` example, when you need to alter the state of variables defined outside the function's local scope.
### 2. Passing Large Objects (Using `const` Reference)
If you want to avoid the overhead of copying a large object but also want to guarantee that the function cannot modify the original object, you should pass it as a **const reference**:
```cpp
void printLargeData(const MyLargeClass &data) {
// 'data' is passed without copying, but cannot be modified
data.display();
}
```
### 3. Returning References
Functions can also return references. This is commonly used in operator overloading (such as the assignment operator `=` or stream insertion operator `<<`) to allow method chaining.
---
## Summary: Call by Value vs. Call by Reference
| Feature | Call by Value | Call by Reference |
| :--- | :--- | :--- |
| **Argument Passing** | Passes a copy of the variable. | Passes an alias (reference) to the variable. |
| **Memory Allocation** | Creates a new memory location for the parameter. | Shares the same memory location as the argument. |
| **Modification** | Changes inside the function do not affect the original variable. | Changes inside the function directly modify the original variable. |
| **Performance** | Slower for large objects due to copy overhead. | Fast; no copying is involved. |
YouTip