ProAnswers.org

what is mean by pass by value and pass by reference in C code?

what is mean by pass by value and pass by reference in C code?

1 Like

Pass By Reference :
-In Pass by reference address of the variable is passed to a function. Whatever changes made to the formal parameter will affect to the actual parameters

  • Same memory location is used for both variables.(Formal and Actual)-
  • it is useful when you required to return more then 1 values

Pass By Value:

  • In this method value of the variable is passed. Changes made to formal will not affect the actual parameters.
  • Different memory locations will be created for both variables.

Pass by Value:

In this method, the value of each of the actual arguments in the calling function is copied into corresponding formal arguments of the called function. In pass by value, the changes made to formal arguments
in the called function have no effect on the values of actual arguments in the calling function.

Example:

#include
void swap(int x, int y) {
int t;
t = x;
x = y;
y = t;
}
int main()
{
int m = 10, n = 20;
printf("Before executing swap m=%d n=%d
", m, n);
swap(m, n);
printf("After executing swap m=%d n=%d
", m, n);
return 0;

}

Output:
Before executing swap m=10 n=20
After executing swap m=10 n=20

Reason:
In the main function, value of variables m, n are not changed though they are passed to function ‘swap’. Swap function has a copy of m, n and hence it can not manipulate the actual value of arguments passed to it.

Pass by Reference: In this method, the addresses of actual arguments in the calling function are copied into formal arguments of the called function. This means that using these addresses, we would have an access to the actual arguments and hence we would be able to manipulate them. C does not support Call by reference. But it can be simulated using pointers.

Example:

#include
/* function definition */
void swap(int *x, int *y) {
int t;
t = x; / assign the value at address x to t */
*x = y; / put the value at y into x */
y = t; / put the value at to y */
}
int main() {
int m = 10, n = 20;
printf("Before executing swap m=%d n=%d
", m, n);
swap(&m, &n);
printf("After executing swap m=%d n=%d
", m, n);
return 0;
}

Output:
Before executing swap m=10 n=20
After executing swap m=20 n=10.

Reason:
In the main function, address of variables m, n are sent as arguments to the function ‘swap’. As swap function has the access to address of the arguments, manipulation of passed arguments inside swap function would be directly reflected in the values of m, n.