C++ - Arguments By Value, By Reference
In C++, functions can have parameters passed by value or by reference. These are known as call by value and call by reference mechanisms. Let's explore each of them:
Call by Value:
When a parameter is passed by value, a copy of the argument is made and passed to the function. Any modifications made to the parameter within the function do not affect the original argument. Here's an example:
void increment(int num) {
num++;
}
int main() {
int number = 5;
increment(number);
std::cout << "Number: " << number << std::endl;
return 0;
}
In this example, the increment function takes an integer num as a parameter and increments it by 1. However, since the parameter is passed by value, any changes made to num within the function do not affect the original number variable in the main function.
Call by Reference:
When a parameter is passed by reference, the memory address of the argument is passed to the function, allowing direct access to the original data. Any modifications made to the parameter within the function will affect the original argument. Here's an example:
void increment(int& num) {
num++;
}
int main() {
int number = 5;
increment(number);
std::cout << "Number: " << number << std::endl;
return 0;
}
In this example, the increment function takes an integer reference num as a parameter. Any changes made to num within the function directly modify the original number variable in the main function since the parameter is passed by reference.