Sunday, August 2, 2009

C++ for beginners?

please explain if the value of pass-by-value can not be changed and the value of pass-by-reference can be changed as well? can it be view the difference this way?

C++ for beginners?
The system could use linux or unix.





Post made by me from previous question here.





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 b 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;


}
Reply:the pass by value doesnot affect the value of original variables, as only the values of the original variables are passed and processed.





but for the pass-by-reference, the address of the original variable is passed and hence the original values are edited.





we must be sure where to use passbyvalue and passbyreference.





for eg. for swapping two variables, pass by reference can be useful.





for adding two numbers pass by value is much simpler.





and,


PC can use Linux or unix.


No comments:

Post a Comment