What is the difference between passing an argument by value and passing an argument by reference?

Passing an argument "by value" to a function means that the called function is given the values of its arguments in temporary variables rather than the originals while in "pass by reference", the caller provides the address of the variable to be set, and the called function must declare the parameter to be a pointer and access the variable indirectly through it.

Example of passing an argument by value

	/* power: raise base to n-th power; n >= 0;  */
	int power(int base, int n)
		int p;
		for (p = 1; n > 0; --n)
		p = p * base;
		return p;

The parameter n is used as a temporary variable, and is counted down until it becomes zero. Whatever is done to n inside power has no effect on the argument that power was originally called with.

Example of passing an argument by reference

	void swap(int *px, int *py)
		int temp;
		temp = *px;
		*px = *py;
		*py = temp;

	swap(&a, &b); /* Calling the swap function above */

Since the operator & produces the address of a variable, &a is a pointer to a. In swap itself, the parameters are declared as pointers, and the operands are accessed indirectly through them.


Passing an argument by reference in C

Pointer arguments enable a function to access and change objects in the function that called it.


  • In C, all function arguments are passed “by value”. To pass “by reference”, the calling program must pass pointers to the values to be changed.
  • When the name of an array is used as an argument, the value passed to the function is the location or address of the beginning of the array – there is no copying of array elements. By subscripting this value, the function can access and alter any argument of the array.

Add comment

Security code