Call by Value and Call by reference in C++
Call by Value
In C++ the Call by Value method takes place , the called function creates its own copies of the original values that have been entered .
Example of Call by value
int main()
{
int x =1;
cout<< "x="<<x;
ch(x);
cout<<"\n x="<<x;
return 0;
}
void ch(int b)
{
b=10;
}
Output
x=1;
x=1;
Any changes , that are made, occur on the called function's copy of values and are not reflected back to the calling function .
Call by Reference
In case of the Call by reference , the method accesses and works with the original values using their references.
Any changes , that occur , take place on the original values and are reflected back to the calling code.
Example of Call by Reference
int main()
{
int a = 1;
cout<< "x="<<x;
ch(a);
cout<<"\n x ="<<x;
return 0;
}
void ch(int &b)
{
b=10;
}
Output
x=1
x=10
No comments:
Post a Comment