Loading, please wait...

Call By Value and Reference

There are two ways to invoke functions in many programming languages call-by-value and call-by-reference. When arguments are passed by value, a copy of the argument’s value is made and passed to the called function. Changes to the copy do not affect an original variable’s value in the caller. When an argument is passed by reference, the caller allows the called function to modify the original variable’s value.

 

Call-by-value should be used whenever the called function does not need to modify the value of the caller’s original variable. This prevents the accidental side effects (variable modifications) that so greatly hinder the development of correct and reliable software systems.

 

Call-by-reference should be used only with trusted called functions that need to modify the original variable.

 

Example

/*Creating and using a programmer-defined function */
#include <stdio.h>

int square( int y ); /* function prototype */

/* function main begins program execution */
int main( void )
{
int x; /* counter */
/* loop 10 times and calculate and output square of x each time */

for ( x = 1; x <= 10; x++ ) {
printf(“%d”, square (x)); //function call
} /* end for */

printf( "\n" );
return 0;
}

/* square function definition returns square of parameter */
int square( int y ) /* y is a copy of argument to function */
{
return y * y; /* returns square of y as an int */
} /* end function square */

Output

1 4 9 16 25 36 49 64 81 100