Pass by Value And Pass by Address

There are two ways to pass arguments to a function -- Pass by Value and Pass by Address. The major difference between Pass by Value and Pass by Address is that in pass by value a copy of actual arguments is passed to respective formal arguments. While, in call by reference the location (address) of actual arguments is passed to formal arguments, hence any change made to formal arguments will also reflect in actual arguments.

Pass by Value:

 A copy of actual arguments is passed to formal arguments of the called function and any change made to the formal arguments in the called function has no effect on the values of actual arguments in the calling function.

 In call by value, actual arguments will remain safe, they cannot be modified accidentally. 

#include<stdio.h>

void swap (int a,int b)

{

          int temp;

          temp=a;

          a=temp;

          b=temp;

          printf("a=%d,b=%d",a,b);

}

int main()

{

          int a=10,b=20;

          swap(a,b);

          printf("a=%d\n,b=%d\n",a,b);

}

output:

          a=20,b=10(in function swap)

          a=10,b=20(in main function)

In the above program, a and b values are updated only in the functon swap not in the main function.

Pass by Address:

In Pass by address, the location (address) of actual arguments is passed to formal arguments of the called function. This means by accessing the addresses of actual arguments we can alter them within from the called function.

alteration to actual arguments is possible within from called function; therefore the code must handle arguments carefully else you get unexpected results.

#include<stdio.h>

void swap (int *a,int *b)

{

          int temp;

          temp=*a;

          *a=temp;

          *b=temp;

          printf("a=%d,b=%d",*a,*b);

}

int main()

{

          int a=10,b=20;

          swap(&a,&b);

          printf("a=%d\n,b=%d\n",a,b);

}

output:

          a=20,b=10(in function swap)

          a=20,b=10(in main function)

In the above program, a and b address are  passed and in the function swap those address are received by the pointers updated  values are reflected to the main function.