Call by Reference and Call by Value - Leo tutorials

Call by Reference :  The called function creates a new set of new set of variable and copies the value of arguments into them. The function does not have access to the actual variable in the calling program and can only work on the copies of values.
          The reference variable in C++ permits to pass parameters to the functions by reference. When ' the arguments is passed by reference, the 'format' arguments in the called function become aliases to the 'actual' arguments in the calling function. This means that when the function is working with its own arguments, it is actually working on the original data. Consider the following function :

      void swap( int a, int b)
      //a and b are reference variables
     {
                int t=a; // dynamic initialization
                a=b
                b=t;
      }
if m and n are two integer variables, then the function call
          swap(m,n);
  will exchange the values of m and n using their aliases (reference variables) a and b. This is accomplished using pointers and indirection as follows :
           void swap1(int *a, int *b)
          //Function definition
{
          int t;
          t= *a; // assign the value at address a to t
          *a= *b; // put the value at b into a
          *b= t; // put the value at t into b
This function can be called as follows :
          swap1(x,y); // call by passing
          address of variables
                 or
          swap1(&x, &y);
In 'call by reference', actual argument is accessed and manipulated, thus the change persists even after the termination of the called function. In C++, normally 'call by value' method is used, but if want to manipulate the actual values of the argument, then we can use the 'call by reference' method. Few advantages of 'call by reference' over 'call by value' are as follows :

  1. We can manipulate the actual values of the variable
  2. String functions can be easily defined with the help of pointers.
  3. More than one values can be returned with the help of this method whereas in 'call by value' method, a function can return only one value at a time.
  4. Array elements can be easily passed between the functions with the help of 'call by reference' method.

Call by Value : In this method, the value of an argument is copied into the formal parameters of the function definition. Thus, changes made in the formal parameter in the body of a function, have no effect on the argument.
        By default C++ uses call by value to pass arguments. In general, this menas that codes within a function body can nnot alter the arguments used to call the function.

Post a comment

0 Comments