There are two ways in which the argument can be passed through a function in C++ Programming.
- Call by Value
- Call by Reference
Let’s go through call by value and call by reference in C++ language one by one.
C++ call by value
The method of call by value copies the actual argument to the formal parameter of the function. In this case, the changes made to the formal parameters within the function will not be affect the actual argument that is original value is not modified.
By default, C++ programming uses call by value to pass arguments.
Let us understand the call by value with an example in C++
Example: Swap the values of two variables in C++ Programming:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #include <iostream> using namespace std; // function declaration and definition together void swapFunc(int x, int y) { int temp; temp = x; x = y; y = temp; return; } //main function int main() { int a = 10; int b = 20; cout << "Before swap, a: " << a << endl; cout << "Before swap, b: " << b << endl; //calling function by passing a and b swapFunc(a, b); cout << "\nAfter swap, a: " << a << endl; cout << "After swap, b: " << b << endl; return 0; } |
Output:
1 2 3 4 5 | Before swap, a: 10 Before swap, b: 20 After swap, a: 10 After swap, b: 20 |
C++ Call by Reference
Here reference refers t the addresses but not the actual value. In this method, we pass the reference of the argument to the formal parameter.
Since the actual and formal parameters share the same address, the changes made inside the function will be reflected outside the function too. Hence, the original value is modified.
we know that the reference that is the is dealt through the pointers in a program. to understand the call by reference type, you need to have basic knowledge of pointers.
Let us understand the call by reference with an example in C++
Example: Swap the values of two variables in C++ Programming:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include <iostream> using namespace std; //user-defined function void swap(int *x, int *y) { int swap; swap = *x; *x = *y; *y = swap; } //main function int main() { int a = 100, b = 200; cout << "Before swap, a: " << a << endl; cout << "Before swap, b: " << b << endl; //calling a value by passing reference swap(&a, &b); cout << "\nAfter swap, a: " << a << endl; cout << "After swap, b: " << b << endl; return 0; } |
Output:
1 2 3 4 5 | Before swap, a: 100 Before swap, b: 200 After swap, a: 200 After swap, b: 100 |