Saturday, 26 May 2012

argument pass in function

 Arguments in function are passed in two ways
  1. Call by value
  2. Call by reference
Call by value : In this method we just pass value of variable in function . so that any change in these values never affect our main value.

  Reason: In this case we passed values that are assigned to new function variables. So if we do any modification applied to function variable not main's variable.

  #include<stdio.h>
   void add(int a, int b)
   int main()
   {
      int i=2 , int j =5;
      add(i,j);
      getch();
    }
   void add(int a, int b)
   {
     a++;
     b++;
   }





here we are passing values of i and j in the function. and change in function never affect to main 's value (i and j).


Call by reference : In this method we just pass address of variable in function. so that any change affect our main value.

Reason: In this case we passed address that are assigned to new function pointer variables whose task to provide alternative way to reach original value in the memory. So if we do any modification applied main's variable

  #include<stdio.h>
   void add(int *a, int *b)
   int main()
   {
      int i=2 , int j =5;
      add(&i,&j);
      getch();
    }
   void add(int *a, int *b)
   {
     *a++;
     *b++;
   }


  


   here we are passing address of i and j in the function. and change in function affect to main 's value (i and j).
  

No comments:

Post a Comment