call by value call by reference

call by reference call by value

call by value

we have seen before that parameter are mentioned in the function definition and they are used to hold the values that are sent by the calling function. so Any changes made to the parameters inside the function do not effect the actual arguments. This mechanism of passing the arguments is called call by value. The other mechanism where arguments passed can be change by changing parameters is called call by reference using pointer.When we pass value from calling function to called function or function defination it is known as call by value

/* program to understand the call by value */
#include<stdio.h>
void
sum(int x,int y);
void main()
{
int a,b;
printf("Enter the value of a \n");
scanf("%d",&a);
printf("Enter the value of b \n");
scanf("%d",&b);
sum(a,b);
return 0;
}
void sum(int x,int y)
{
int sum;
sum=x+y;
printf("\nSum of a and b=%d",sum);
}

call By Reference in C

The call by reference is a method of passing arguments to a function copies the address of argument into the formal parameter. Inside function the address is used to access the actual arguments or the value of actual arguments in the calling. That means changes made to the original variables.To pass a value by reference,argument pointers are passed to the called function just like any other value. lets take the example to understand call by reference

/* program to understant the call by reference */
#include<stdio.h>
void
swapn( int *num1, int *num2 )
{
int temp ;
temp = *num1 ;
*num1 = *num2 ;
*num2 = temp ;
}
int main( )
{
int n1 = 50, n2 = 30 ;
printf("Before swapping:");
printf("\nn1 is %d", n1);
printf("\nn2 is %d", n2);
/*calling swap function*/
swapn( &n1, &n2 );
printf("\n After swapping :");
printf("\n n1 is %d", n1);
printf("\n n2 is %d", n2);
return 0;
}