Call by Reference and Call by Value
Call by Value and Call by Reference are two ways of passing parameters to a function.
Call by Reference -> modifies the passed value in the main function or the calling function
-> actual arguments are passed to function
-> can be done using pointers or references
Call by Value -> does not modify value in the main function
-> copy of arguments is passed to function
Example,
void modref( int & x ) { x = 0; } // call by reference using reference
void modp (int * x ) { *x = 1; } // call by reference using pointer
void nomod (int x ) { x = 30; } // call by value
int main()
{
int y = 20;
cout<<y<<endl; // 20
modref(y);
cout<<y<<endl; // 0
modp(&y);
cout<<y<<endl; // 1
nomod(y);
cout<<y<<endl; // 1
}
Comments
Post a Comment