Call by Value:
- Calling the function by passing value as parameter.
- We collect the value into an argument of function.
- Arguments are working like local variables.
- Processed arguments can access only from same function.
#include<stdio.h>
void swap(int, int);
int main()
{
int a=10, b=20;
printf("Before Swap : %d \t %d \n", a, b);
swap(a, b);
printf("After Swap : %d \t %d \n", a, b);
return 0;
}
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
Call by Reference:
- Calling the function by passing address as parameter.
- We store address only into pointer variable.
- We use pointer type argument in the function definition to store that address.
- The modified data using the reference can access from the calling function.
#include<stdio.h>
void swap(int*, int*);
int main()
{
int a=10, b=20;
printf("Before Swap : %d \t %d \n", a, b);
swap(&a, &b);
printf("After Swap : %d \t %d \n", a, b);
return 0;
}
void swap(int* a, int* b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}