Wednesday, March 28, 2018

Write a C++ program to implement call by value and call by reference


AIM: Write a C++ program to implement call by value and call by reference.

THEORY:

In call by value, original value is not modified.
In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().In call by reference, original value is modified because we pass reference (address).
Here, address of the value is passed in the function, so actual and formal arguments share the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.
Note: To understand the call by reference, you must have the basic knowledge of pointers.

SOURCE CODE:
#include<iostream>
using namespace std;
void byval(int);
void byref(int &);
void byadd(int *);
int main()
{
            int x;
            cout<<"\n enter the value of x:";
            cin>>x;
            byval(x);
            cout<<"\n after call by valuex is:"<<x<<"\n";
            cout<<"\n before call by reffernce:"<<x<<"\n";
            byref(x);
            cout<<"\n after call by refference x is:"<<x<<"\n";
            cout<<"\n before call by address:"<<x<<"\n";
            byadd(&x);
            cout<<"\n after call by address x is:"<<x<<"\n";
}
void byval(int m)
{
            m=m+10;
}
void byref(int &m)
{
            m=m+10;
}
void byadd(int *m)
{
            *m=*m+10;
}

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home