In C++, function parameters can be passed either by value or by reference. The main difference between these two methods is that pass-by-value makes a copy of the parameter, while pass-by-reference passes a reference to the original parameter.
Pass-by-value: When a parameter is passed by value, a copy of the parameter is made and passed to the function. This means that any changes made to the parameter inside the function will not affect the original value of the parameter outside the function. For example:
void increment(int x) {
x++;
}
int main() {
int myValue = 5;
increment(myValue); // pass-by-value
std::cout << "Value is: " << myValue << std::endl; // prints 5
return 0;
}
In this example, the increment() function takes an integer parameter x by value. Inside the function, the value of x is incremented by 1. However, this change does not affect the value of myValue outside the function, since a copy of myValue was passed to the function.
Pass-by-reference: When a parameter is passed by reference, a reference to the original parameter is passed to the function. This means that any changes made to the parameter inside the function will also affect the original value of the parameter outside the function. For example:
void increment(int& x) {
x++;
}
int main() {
int myValue = 5;
increment(myValue); // pass-by-reference
std::cout << "Value is: " << myValue << std::endl; // prints 6
return 0;
}
In this example, the increment() function takes an integer parameter x by reference, indicated by the ampersand (&) symbol. Inside the function, the value of x is incremented by 1. This change also affects the value of myValue outside the function, since a reference to myValue was passed to the function.
In summary, the main difference between pass-by-value and pass-by-reference in C++ function parameters is that pass-by-value makes a copy of the parameter, while pass-by-reference passes a reference to the original parameter. Pass-by-value is useful when you want to protect the original value of the parameter from being modified by the function, while pass-by-reference is useful when you want the function to modify the original value of the parameter.