Difference Between Call By Value & Call By Reference

This article explains the difference between call-by-value and call-by-reference.

In call by value method, function is called with actual value of the variable.
In call by reference method, function is called with addresses of variable.

In call by value, duplicate copy of original values are passed to user defined function.
In call by reference, original values are referenced from user defined function.

Changes made from user defined function does not affect original values in call by value
Changes made from user defined function affects original values in call by reference.

Using call by value method only one value can be returned from function using return keyword.
Using call by reference method multiple values can be returned from function without using return keyword.

Call-By-Value Example:

#include
#include
void swap(int a, int b);
void main()
{
int a=10, b=20;
printf(“Before swap: a=%d and b=%d\n”,a,b);
swap(a,b); /* Call by Value */
printf(“After swap: a=%d and b=%d\n”,a,b);
getch();
}
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
Output:
Before swap: a = 10 and b = 20
After swap: a = 10 and b = 20
Call-By-Reference Example:

#include
#include
void swap(int *p, int *q);
void main()
{
int a=10, b=20;
printf(“Before swap: a=%d and b=%d\n”,a,b);
swap(&a, &b); /* Call by Refernce */
printf(“After swap: a=%d and b=%d\n”,a,b);
getch();
}
void swap(int *p, int *q)
{
int temp;
temp = *p;
*p = *q;
*q = temp;
}
Output:
Before swap: a = 10 and b = 20
After swap: a = 20 and b = 10