C++ Call by Value and Call by Reference

In C++, there are two ways to pass arguments to a function: call by value and call by reference. The method of passing arguments to a function can greatly affect the behavior of your program, so it is important to understand the difference between these two methods. In this article, we will explore the basics of call by value and call by reference in C++ and how to use them in your programs.

Call by Value

Call by value is the most common method of passing arguments to a function in C++. When you pass an argument to a function by value, a copy of the argument is made and passed to the function. Any changes made to the argument within the function are not reflected in the original argument outside of the function. For example, consider the following code:

1void doubleValue(int x) { 2 x = x * 2; 3} 4 5int main() { 6 int num = 5; 7 cout << "Before: " << num << endl; 8 doubleValue(num); 9 cout << "After: " << num << endl; 10 return 0; 11}

Output:

1Before: 5 2After: 5

In this example, we have a function doubleValue that takes an int argument x and multiplies it by 2. When we call doubleValue and pass num as an argument, a copy of num is made and passed to the function. Within the function, the value of x is multiplied by 2, but this change is not reflected in the original value of num. When we print the value of num to the console both before and after calling doubleValue, we see that it remains 5.

Call by Reference

Call by reference is a method of passing arguments to a function where the function receives a reference to the original argument instead of a copy. Any changes made to the argument within the function are reflected in the original argument outside of the function. To pass an argument to a function by reference, you can use the & operator in the function prototype and call. For example, consider the following code:

1void doubleValue(int &x) { 2 x = x * 2; 3} 4 5int main() { 6 int num = 5; 7 cout << "Before: " << num << endl; 8 doubleValue(num); 9 cout << "After: " << num << endl; 10 return 0; 11}

Output:

1Before: 5 2After: 10

In this example, we have a function doubleValue that takes an int reference argument x. When we call doubleValue and pass num as an argument, a reference to num is passed to the function. Within the function, the value of x is multiplied by 2, and this change is reflected in the original value of num. When we print the value of num to the console both before and after calling doubleValue, we see that it has been changed from 5 to 10.