Call by reference passes the address of the variable.
Call by value makes a copy of the variable.
If you change the value in the variable when passing by reference you will also change the value in the variable in the previous function.
If you change the value in the variable when passing by value the value in the variable in the previous function will remain the same.
Example code is included so you can see the difference.
#include %26lt;iostream%26gt;
using namespace std;
void call_by_value(int x,int y);
void call_by_reference (int %26amp;x,int %26amp;y);
int main()
{
int a=1;
int b=2;
call_by_value(a,b);
cout%26lt;%26lt;a%26lt;%26lt;' '%26lt;%26lt;b%26lt;%26lt;endl; //a is still 1 and b is still 2
call_by_reference(a,b);
cout%26lt;%26lt;a%26lt;%26lt;' '%26lt;%26lt;b%26lt;%26lt;endl; //a is now 5 and y is now 3
return 0;
}
void call_by_value(int x,int y)
{
x=5;
y=3;
}
void call_by_reference (int %26amp;x,int %26amp;y)
{
x=5;
y=3;
}
What is a function call by value and call by reference in C++?
call by reference is the instance variable numX. call by value is what numX contains 54
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment