Copyright © Programs ++
Design by Dzignine
Friday 20 January 2012

Call by reference


In call by reference, the address of the variables is passed rather than its copy, so any changes in the address will be reflected in the values of the original variables. Call by reference is useful when permanent changes are needed in the value of the arguments. A sample program is as follows :

 // Program to show call by reference

#include<iostream.h>


void swapArgs(int *a,int *b) // function to swap arguments using reference
{
    int *temp; // to store the address of a
    temp = a;
    a = b;
    b = temp;
}

int main()
{
    int x = 5;
    int y = 10;
    cout<<" Value of x and y before swap : "<<x<<" "<<y;
    cout<<endl;
    swapArgs(&x,&y);
    /* as the address of x and y is passed as arguments, any changes to these arguments
       will result in changes to the original values */
    cout<<" Value of x and y after swap : "<<x<<" "<<y;
    return 0;
} // end of main










------ Related Posts ------

0 comments:

Post a Comment

Comment Here....