Passing and Returning by reference | C++ Programming

Passing by references in C++ Programming

         We can pass parameters in function in C++ by reference. When we pass arguments by reference, the  formal arguments in the called function become aliases to the  actual arguments in the calling  function i.e. when the function is working with its own arguments, it is actually working on the original data.

Example
 void fun (int &a) //a is reference variable { a=a+10; } 

int main()
{
int x=100;//CALL
cout< //a is reference variable{a=a+10;}int main(){ int x=100;fun(x);  //CALL cout< 

//prints 110

when function call fun(x) is executed, the following initialization occurs:  int &a=x; i.e. a is an alias for x and represents the same data in memory. So updating in function causes the update of the data represented by x. this type of function call is known as Call by reference.


 //pass by reference


#include<iostream.h>

#include<conio.h>
void swap(int &, int &);
 void main() {  int a=5,b=9;
cout<<"Before Swapping: a="<
swap(a,b);//call by reference
cout<<"After Swapping: a="<
getch(); }
 void swap(int &x, int &y)
{
int temp;
temp=x;
x=y;     
y=temp;
}


Return by reference 

       A function can return a value by reference. This is a unique feature of C++. Normally function is invoked only on the righthand side of the equal sign. But we can use it on the left side of equal sign and the value returned is put on the right side.  



//returning by reference from a function as a parameter 

#include<iostream.h>
int x=5,y=15;//globel variable
int &setx();
void main()
{
setx()=y;    //assign value of y to the variable    //returned by the function
cout<<"x="<

getch();
}
int &setx() {    //display global value of x   

cout<<"x="<

return x;
} 

Post a Comment

0 Comments