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 in the pass by value copy of actual arguments is passed to respective formal arguments. While, in the 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 does not affect the values of actual arguments in the calling function.

Incall 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 function and not swap 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. That means by accessing the addresses of actual arguments we can alter them within 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 addresses are passed and in the function swap those addresses are received by the pointers updated values are reflected in the main function.

Enquire Now

Enquire Now

Enquire Now

Please Sign Up to Download

Please Sign Up to Download

Enquire Now

Please Sign Up to Download

Enquiry Form

Quick Enquiry