In traditional C call by value is used in function call. But in C++ call by reference is used.
Let we understand how call by value and call by reference by the help of swap function , Also know their working and implementation.
CALL BY VALUE
void swap ( int a , int b )
{
int temp ;
temp = a ;
a = b ;
b = temp ;
cout << a << b ;
}
void main ( )
{
int x , y ;
x = 10 ;
y = 20 ;
cout << x << y ;
swap ( x , y ) ;
cout << x << y ;
}
Output :
x = 10 , y = 20
a = 20 , b = 10
x = 10 , y = 20
Explanation :
Here in call by value method it is clear that in swap function void swap ( int a , int b ) value of a & b can be change so it known as formal arguments. But the final value of a & b is x & y in main () function swap ( x , y ) which can not change so it is known as actual argument.
Now from the above details we can say that changes takes place in formal arguments does not reflect in actual arguments.
Above diagram show that formal values are change but Actual values will remain same.
No comments:
Post a Comment