Call by value and call by reference in C++ Language
In C++ language, there are two methods to pass value or data to a function -
- Call by value
- Call by reference
In call by value method the original value does not changed whereas It changed in call by reference method.
Let us understand call by value and call by reference one by one in detail -
Call by value in C++
In call by value, the original value is not changed. The value which is passed to any function is stored by the function parameter in the stack memory location. If you change the values of a function parameter, it is changed only for the current function. It never changes the value of variable inside the caller method such as main() function.
Let's try to understand the concept of call by value with an example given below -
Output -
Value of the data is : 3
Call by reference in C++
In call by reference, the original value is modified as we pass the reference (address).
Here, the address of values are passed to the function parameters, by which the actual and formal arguments share the same address space. Therefore, the value changed inside the function is reflected inside as well as outside.
Note : To understand call by reference, you need to have basic knowledge of pointers.
Output -
Value of x is: 200
Value of y is: 100
Difference between call by value and call by reference
No. | Call by value | Call by reference |
---|---|---|
1 | A copy of the value is passed to the function. | An address of value is passed to the function. |
2 | Changes made inside the function is not reflected on other functions. | Changes made inside the function is reflected outside the function also. |
3 | Actual and formal arguments are be created in different memory location. | Actual and formal arguments are be created in same memory location. |
Also check out this : C++ Functions - Learn With AVRK