Friday, February 28, 2014

What is pass by reference in c++

This is my first tutorial about c++ and in this I’m going to show you how the pass an argument by reference in a function. While using pass by reference in a function we have to use pointers. Passing parameters by reference has the functionality of pass by pointer and the syntax of the pass value. The function body and call to it is identical to that of pass by value, but has the effect of pass by pointer. To pass parameters by reference,
the function call is similar to that of pass by value. In function declaration, those parameters, which are to be received by reference must be preceded by & operator. When the parameters are referenced, the called function receives the ” lvalues” of the parameters rather than a copy of its value. Lvalue means, an expression that can appear on the left side of an assignment operator. This means that the function knows where the actual parameters reside in memory and can therefore change their values or take their address. This is shown in the following example.

#include<iostram.h>

void swap(int &x,int &y)
{
    int i;
   
    cout << "In swap function,before exchange x="<<x<<"y="<<y<<endl;
  
    t=x,x=y,y=t;
   
    cout << "In swap function,after exchange x="<<x<<"y="<<y<<endl;
}

void main()
{
   int a;
    
   int b;
   
   cout << "Please Enter two integers";
  
   cin >>a>>b;
   
   cout << "In main function,before calling swap funtion a=" << a << "b=" <<b <<endl;
  
   swap(a,b);   
   
   cout << "In main function,after calling swap funtion a=" << a << "b=" <<b <<endl;
}


        In the above program is for swapping two integers. In this, first we created a function called swap with two reference variables. As you know the program starts execution from the main function. We used two local variable or auto variables in the main function for storing the input from the user. When the program starts, it waits for the user to give two integers to the program. When we enter the two values required by the program and hit enter key or the return key, first it displays the value that we have entered first then it show the value from the function. That is the value received by the function by the reference. You might have think that what is the difference between the pass by address and pass by reference. Don’t confuse with that. These two are entirely different from each other. In pass by address the arguments or parameter of the function that we are going to create will be pointer variables. And the only similarity is the use of the & symbol in while passing and receiving arguments or parameters In this program we didn’t used any object oriented feature of C++, because it’s just an illustration of the pass by reference in c++ programming language.  We will also talk about the other value passing mechanisms like pass by value, pass by address.

No comments:

Post a Comment