FoodForFutureGeeks

Thursday 5 April 2012

Functions Pass By Value & Pass By Reference

We can pass arguments to a function in two ways:

Pass by Value:

Only the value of the variable is passed on to a function, this value is stored in a formal parameter of function, any manipulations done by the function will not be reflected back to the actual variable.

Pass by Reference:

Here the address of the variable is passed, this will be received by the formal argument which is a pointer, the formal argument acts as a reference to the original variable, so any changes made using the function will be reflected back to the actual parameter.

Example program:
Pass by Value


#include<stdio.h>
//function declaration
void add(int var1,int var2,int result);

//main function
void main()
{
 int result=0,var1=10,var2=20;
 printf("before passing by value:\nresult:%d",result);
 //pass the variable result by value
 add(var1,var2,result);
 printf("\nafter passing by value:\nresult:%d",result);

}
//function definition for add function
void add(int var1,int var2,int result)
{
result=var1+var2;
}

output:

before passing by value:
result:0
after passing by value:
result:0


we see that even though in the add function we are storing the sum of var1,var2 in result its not reflected in main function as the variables are passed by value.

Pass by Reference:


#include<stdio.h>
//function declaration
void add(int var1,int var2,int* result);

//main function
void main()
{
 int result=0,var1=10,var2=20;
 printf("before passing by Reference:\nresult:%d",result);

 //pass the variable result by Reference
 add(var1,var2,&result);
 printf("\nafter passing by Reference:\nresult:%d",result);

}
//function definition for add function
void add(int var1,int var2,int* result)
{
 *result=var1+var2;
}



before passing by Reference:
result:0
after passing by Reference:
result:30

we see that since the result was passed by reference, the changes done in the add function are reflected back to main function.

Figure showing pass by value&pass by reference



No comments:

Post a Comment