The default method of passing arguments to a C function is by value (Pass-by-Value) which we explained in the chapter Passing Arguments. In this method the value of the argument is copied into to the function. Any changes that you make to these arguments inside the function are not visible to the calling function.
Another method of passing arguments to a function is Pass-by-Reference. In this method a pointer to the argument variable is passed to the function. Any change you make to the pointer's value inside the function will also be reflected in the calling function.
#include <stdio.h> void count_update(int *, int *); void count_update(int *iptr, int *jptr) { *iptr = *iptr + 1; *jptr = *jptr + 2; printf("The value of iptr inside count_update function is %d \n", *iptr); printf("The value of jptr inside count_update function is %d \n", *jptr); return; } main() { int i, j; int *iptr, *jptr; i = 10; j = 15; iptr = &i; jptr = &j; count_update(iptr, jptr); printf("The value of iptr inside main function is %d \n", *iptr); printf("The value of jptr inside main function is %d \n", *jptr); return 0; } }
The output of this program is
The value of iptr inside count_update function is 11 The value of jptr inside count_update function is 17 The value of iptr inside main function is 11 The value of jptr inside main function is 17
In this example the variables iptr
and jptr
are pointers to variable i
and j
respectively. These pointer varibles as passed as arguments to the count_update()
function. The value of the pointers are changed inside the count_update()
function and those changes are available inside the main()
function also.
In C a function can return only one value. Pass by Reference method can be used to return multiple values from a function.
Nothing yet..be the first to share wisdom.