When passing a parameter by value, only a copy of the parameter is passed into the procedure. This means that the original parameter cannot be modified inside the procedure. Advantage of passing by value is its simplicity and the fact that the procedure does not have access to (and possibly modifying) the actual parameter. Disadvantage is that passing large parameters such as arrays and structures are inefficient due to the copy. Also, if the procedure has to return value to calling function, only option is return value of the function.
Example code showing pass by value in C language:
void SetToZero(int inputParam)
{
-
inputParam = 0; /* The formal parameter is modified */
}
int main(void)
{
-
int actualParameter = 7;
SetToZero (actualParameter);
printf(ā\n Parameter after procedure invocation %dā, actualParameter); /* actualParameter is still 7 */
return 0;
}
When passing by reference, the actual location (address in memory) of the parameter is passed. So in case of pass by reference, the procedure can modify the actual parameter. C supports only passing by value ā but passing by reference may be emulated by using pointers as arguments. C++ supports true passing by reference; example is given below:
void SetToZero(int &ioParam)
{
-
ioParam = 0; /* The actual parameter is also modified */
}
int main(void)
{
-
int actualParameter = 7;
SetToZero (actualParameter);
cout < < " Parameter after procedure invocation is " << actualParameter << " \n"; /* actualParameter is now 0 */
return 0;
}