We have seen that in a C program, the function arguments are call by value by default. Which means that when we pass arguments into a function, a copy of those arguments is created instead of using the actual variables which have been passed.
void foo(int x, int y)
{
x = 50; /* does not affect the value of a because x is copy of a */
y = 100; /* does not affect the value of b because y is copy of b */
return;
}
void main()
{
int a = 10;
int b = 20;
foo(a, b); /* the actual arguments passed to the function are a and b */
printf("a = %d, b = %d\n"); /* after calling function foo(), value of a is 10 and b is 20 */
return;
}
So if we need to get the values of a and b modified by the function foo(), we need to use call by reference. Formally, there is no mechanism in C for call by reference. But pointers help us out by providing this functionality.
void foo(int* px, int* py)
{
*px = 50; /* since px is pointing to a, *px is reference to a */
*py = 100; /* since py is pointing to b, *py is reference to b */
return;
}
void main()
{
int a = 10;
int b = 20;
foo(&a, &b); /* the actual arguments passed to the function are a and b */
printf("a = %d, b = %d\n"); /* after calling function foo(), value of a is 50 and b is 100 */
return;
}
In the above example, we pass the address of variables a and b to the function foo() which accepts pointers to integer as arguments. So when we reference the variables by using the dereference operator on px and py, we are referencing the actual variables a and b. This causes their value to be modified in the calling function.
This is further simplified in the figure shown below:

An array is handled specially when it is passed as an argument. Instead of copying the entire array, just a pointer to the first element of the array is passed as a parameter (which in fact is passing the array by reference). So any changes made to the array passed as a formal argument will reflect into the actual argument.
void foo(int pArray[]) /* array passed as call by reference. could also be int *pArray */
{
int i = 0;
for(i=0; i<10; i++)
{
pArray[i] = 100; /* changes the value of array a in the main() */
}
return;
}
void main()
{
int a[10];
foo(a); /* the actual arguments passed to the function are a and b */
return;
}




