Friday, July 17, 2020

Call By Reference Method

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.

For understanding Call By Reference in C++. let we first understand Call By Pointer in C.

CALL BY POINTER IN C

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 ;

}

Explanation :

Here in above example int *a and int *b is pointer to integer type of variable. In C & (Ampersand) is used to indicate address but in C++ it is used as reference.





CALL BY REFERENCE IN C++

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 :

In C & (Ampersand) is used to indicate address but in C++ it is used as reference. 

Suppose if

 int a = 5 ;

 int &b = a;

In above statement &b = a it doesn't means that the value of a assign in address of b. But it mean that b is only the another or second name of a , So if a = 5 than b = 5. this is the concept of reference.
When we pass argument by reference the formal argument in called function will only change our name of actual argument in calling function. This mean that when the function is working with its own arguments it is actually working on the original data.


No comments:

Post a Comment