C++ Program to illustrate the difference between call by value and call by reference [DEVCPP/GCC]

CALL BY VALUE

In call by value, a copy of actual parameter is passed to the calling function. The passed value to the function is locally stored by the function parameter in stack memory. Here both formal parameters and actual parameters share different address apace. Thus any changes in formal parameters is not reflected back in actual parameters.

CALL BY REFERENCE

In call by reference, reference(address) of the actual parameters is passed to the calling function (See Reference Variables). It results in creation of alias for the actual parameters and both actual parameters and formal parameters refers to the same memory location. Thus any changes in formal parameters is reflected back in actual parameters.

PROGRAM

// Program to illustrate the difference between call by value and call by reference

#include <iostream>

using namespace std;

void callByValue(int n)
{
        n=n*n;
        cout<<"\nNUM IN FUNCTION: "<<n;
}

void callByReference(int &n)
{
        n=n*n;
        cout<<"\nNUM IN FUNCTION: "<<n;
}

int main()
{
        int num;

        cout<<"\nENTER A NUMBER: ";
        cin>>num;

        cout<<"\n\nCALLING BY VALUE!\n";
        callByValue(num);

        cout<<"\nNUM IN MAIN: "<<num;

        cout<<"\n\nCALLING BY REFERENCE!\n";
        callByReference(num);

         cout<<"\nNUM IN MAIN: "<<num;
 return 0;
}

OUTPUT

C++ Program to illustrate the difference between call by value and call by reference with output

Share this

Related Posts

1 comments :

comments

FIND US ON FACEBOOK!