Parameter Passing

download Parameter Passing

of 10

description

Parameter Passing ppt

Transcript of Parameter Passing

  • PARAMETER PASSING METHODS

  • TYPESParameter passing :Giving data's from calling function to called function .Call by valuePassing copy of the variable Call by referencePassing address of the variable

  • CALL BY VALUE

    While Passing Parameters using call by value ,xerox copy of original parameter is createdand passed to the called function.Any update made inside method will not affect theoriginal value of variable in calling function.

  • Swapping two values using call by value #include void swap(int x,int y) ;void main() { int a=50,b=70; swap(a,b); printf("\n a =%d,a);printf("\n b=%d",b); } void swap(int x, int y) { int temp; temp = x; x = y; y = temp; }Outputa= 50b=70

  • In the above example a and b are the original values and Xerox copy of these values is passed to the function and these values are copied into x,y variable of swap function respectively.As their scope is limited to only function so theycannot alter the values inside main function.

  • CALL BY REFERENCE

    While passing parameter using call by reference (or call by address) scheme , we arepassing the actual address of the variableto the called function.Any updates made inside the called functionwill modify the original copy, since we are directlymodifyingthe content of the exact memory location.

  • Swapping two values using call by refernce#include void swap(int *x,int *y) ;void main() { int a=50,b=70; swap(&a,&b); printf("\n a =%d,a);printf("\n b=%d",b); } void swap(int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; }Outputa= 70b=50

  • In the above example a and b are the actual values and address of these values is passed to the swap function and these address are copied into x,y pointer variable of swap function respectively.Any updates made inside the called functionare directlymodifyingthe content of the original copy.Because it works with exact memory location.

  • Call by value#include void addvalue(int ); int main() { int a=10; printf(\n a = %d before function call", a); addvalue(a); printf(\n a = %d after function call", a); return 0; }

    void addvalue(int x) { x += 10; printf(\n Inside addvalue function , x = %d , x); }outputa = 10 before function call Inside addvalue function x =20 a = 10 after function call.

  • Call by reference#include void addvalue(int* ); int main() { int a=10; printf(\n a = %d before function call", a); addvalue(&a); printf(\n a = %d after function call", a); return 0; }

    void addvalue(int *x) { *x += 10; printf(\n Inside addvalue function , x = %d , *x); }outputa = 10 before function call Inside addvalue function x =20 a = 20 after function call.