C Tutorial Reference parameter technique
Introduction to functions in C
Void functions
Call by Value and call by reference
Swap example
Reference parameter technique

Bigger pointer example




To pass an object X as a reference parameter, the programmer must pass a pointer to X

instead of X itself. The formal parameter will be a pointer to the value of interest. The

caller will need to use & or other operators to compute the correct pointer actual

parameter. The callee will need to dereference the pointer with * where appropriate to

access the value of interest. Here is an example of a correct  Swap() function.


static void Swap(int* x, int* y) {     // params are int* instead of int int temp;


temp = *x;        // use * to follow the pointer back to the caller's memory

*x = *y;

*y = temp;


// Some caller code which calls Swap()...

int a = 1;

int b = 2;


Swap(&a, &b);



Things to notice...


The formal parameters are int* instead of int.


The caller uses & to compute pointers to its local memory (a,b).


The callee uses * to dereference the formal parameter pointers back to get the caller's memory.


Since the operator & produces the address of a variable --  &a is a pointer to a. In Swap() itself, the formal parameters are declared to be pointers, and the values of interest (a,b) are accessed through them. There is no special relationship between the

names used for the actual and formal parameters. The function call matches up the actual and formal parameters by their order -- the first actual parameter is assigned to the first formal parameter, and so on. I deliberately used different names (a,b vs x,y) to emphasize that the names do not matter.

Want To Know more with

Video ???

Contact for more learning: webmaster@freehost7com