C Language: Pointers and functions – Call by value

Pointers and functions

Comparison between call by value and call by reference

A function may be invoked in two ways
(a) Call by value
(b) Call by reference

Call by value:

In this method, the value of each actual argument(a,b) in the calling function is copied on to the corresponding formal arguments(p,q) of the called function.

The called function works with and manipulates its own copies of arguments and because of this, changes made to the formal arguments in the called function have no effect on the values of the actual arguments in the calling function.

In call by value if we modify the values of the arguments passed to the called function within the called function then those modifications are visible only within the called function they are not visible in the calling function.

Example:1

```//to swap two values using call by value
#include<stdio.h>
#include<conio.h>
void swap(int p,int q);
int main()
{
int a,b;
printf("Enter 2 numbers ");
scanf("%d %d",&a,&b);
swap(a,b);
printf("in main function\n");
printf("1st value %d 2nd value %d\n",a,b);
getch();
return(0);
}
void swap(int p,int q)
{
int t;
t=p; //1
p=q; //2
q=t; //3
printf("In swap function\n");
printf("1st value %d 2nd value %d\n",p,q);
}
```
```/* Output */

Enter 2 numbers 10
20
In swap function
1st value 20 2nd value 10
in main function
1st value 10 2nd value 20```

Example:2

```//call byvalue
#include<stdio.h>
#include<conio.h>
void abc(int n)
{
n=100;
}
int main()
{
int a=10;
printf("a= %d\n",a);
abc(a);
printf("a= %d\n",a);
getch();
return(0);
}
```
```/* Output */

a= 10
a= 10```

Important Pages