C language : Call by value, call by Reference

In C, there is a concept call ‘Call By Value’, and the best way to explain is to use a code example:

#include <stdio.h>

void swap(int x, int y) {
	int z = x;
	x = y;
	y = z;
	printf("x and y has been swap: x = %d, y = %d\n", x, y);
}

int main(void) {
	int x = 20;
	int y = 11;

	swap(x, y);
	printf("x and y in main: x = %d, y = %d\n", x, y);

	return 0;
}

The above code is to swap 2 variables x and y, by using a function call swap. The code will print the values of x and y after going thru the function and also the x and y values after the function within the main. The result is a follows:

x and y are initialized as x = 20, y = 11, after the swap function, x = 11, y = 20, ok that’s right. But the printf in main (line15) showed that x is still 20 and y is still 11.

This is because when the variables are passed to swap function, only the value is passed (hence call by value or aka pass by value). The function at runtime will create 2 new temporary locations for storing the value and will be destroyed after the function ends. The initial values at the original addresses are untouched, which is shown by the main function printf statement.

Call by Reference

To solve the above issue, we need to use pointers and pass the address of the variable to the swap function. This is known as Call by reference or Pass by Reference. Below code shows call by reference.

#include <stdio.h>

void swap(int *x, int *y) {
	int z = *x;
	*x = *y;
	*y = z;
	printf("x and y has been swap: x = %d, y = %d\n", *x, *y);
}

int main(void) {
	int x = 20;
	int y = 11;

	swap(&x, &y);
	printf("x and y in main: x = %d, y = %d\n", x, y);

	return 0;
}

So, the call by reference method changes the value of the variables, this is because the address of the 2 variables are passed to the swap function by using pointers. Hence the term Call By Reference (aka Pass By Reference).