C++ pass by reference
Created By: chatGPT
C++ offers a way to pass arguments to functions by reference, which allows you to modify the actual value of the variable passed to the function. This can be particularly useful for optimizing performance, especially with large objects, as it avoids unnecessary copies. When you pass by reference, the function receives a reference to the original variable, meaning any modifications will be reflected in the original variable outside the function. Here's how to do it:
void updateValue(int &ref) {
ref += 10; // Modifies the original variable
}
int main() {
int number = 5;
updateValue(number); // Pass by reference
std::cout << number; // Output will be 15
return 0;
}
In the example above, the function updateValue takes a reference to an integer as its parameter. The
&
symbol indicates that we are passing by reference. When we call updateValue with number
, we are passing the actual variable, not a copy. Any changes made to ref
inside the function directly affect number
.void increment(int &value) {
value++;
}
int main() {
int count = 0;
increment(count);
std::cout << count; // Output will be 1
return 0;
}
You can also use const references to pass parameters without modifying the original variable. This is useful for performance optimization while ensuring the data remains unchanged within the function. Here's an example:
void displayValue(const int &value) {
std::cout << value;
}
int main() {
int number = 42;
displayValue(number); // number remains unchanged
return 0;
}
Summary: Passing by reference in C++ allows for efficient function parameter handling and the ability to modify the original variable. Remember:
- Use
&
to indicate a reference parameter. - Use
const &
when you want to ensure that the parameter is not modified.
// Passing by reference example
void exampleFunction(int &num) {
num *= 2; // Original value modified
}
int main() {
int value = 10;
exampleFunction(value);
std::cout << value; // Output will be 20
return 0;
}