| EXAMPLE OF PASS BY REFERENCE | |||||||
| #include<stdio.h> | |||||||
| /* function prototype - the middle argument is the pointer */ | |||||||
| void fun1(int,int*,char); | |||||||
| /* function prototype - the 1st & 3rd arguments are pointers */ | |||||||
| void fun2(int*,int,char*); | |||||||
| int main() | |||||||
| { | |||||||
| /* declare variables */ | |||||||
| int num1, num2; | |||||||
| char ch; | |||||||
| Variable Values at Initialization | |||||||
| /*initialize variables */ | num1 | 10 | |||||
| num1=10; | num2 | 15 | |||||
| num2=15; | ch | A | |||||
| ch='A'; | |||||||
| /* fun1 is called */ | |||||||
| Variable Values after return from fun1 | |||||||
| fun1(num1, &num2, ch); | num1 | 10 | |||||
| num2 | 30 | ||||||
| /* Notice only num2 changed */ | ch | A | |||||
| /* This is because it's a call by reference */ | |||||||
| /*fun2 is called */ | |||||||
| Variable Values after return from fun2 | |||||||
| fun2(&num1,num2,&ch); | num1 | 11 | |||||
| num2 | 30 | ||||||
| /* This time only num1 and ch changed */ | ch | G | |||||
| /* because their addresses were passed */ | |||||||
| /* to the function */ | |||||||
| return 0; | |||||||
| } /* end of function main */ | |||||||
| void fun1(int a, int *b, char v) | |||||||
| { | |||||||
| /* num1's value is passed to fun1 and */ | |||||||
| /* stored in a. num2's address is passed to */ | |||||||
| /* fun1 where it is refered to as b, */ | |||||||
| /* any change here is reflected back in main */ | |||||||
| /* ch's value is also passed to fun1 and */ | |||||||
| /* stored in v. one is a local variable to fun1 */ | |||||||
| /* and is known only in fun1 */ | |||||||
| int one; | |||||||
| one=a; | Variable Values at the end of fun1 | ||||||
| a++; | a | 11 | |||||
| *b=*b * 2; | *b | 30 | |||||
| v='B'; | v | B | |||||
| } | one | 10 | |||||
| /* end of fun1 *; | |||||||
| void fun2(int *x, int y, char *w) | |||||||
| { | |||||||
| /* x is a pointer to num1 in main */ | |||||||
| /* y is passed the value from num2 in main */ | |||||||
| /* w is a pointer to ch in main */ | |||||||
| *x=*x+1; | Variable Values at the end of fun2 | ||||||
| y*=2; | *x | 11 | |||||
| *w='G'; | y | 60 | |||||
| } | *w | G | |||||
| /* end of fun2 */ | |||||||
| Return to 1336 home page | |||||||