C Language: Pointers and functions – Call by reference

Call by reference:

This method can be used in two ways:

(i). Bypassing the pointers
(ii). Bypassing the reference

Bypassing the pointers

When the pointers are passed to the function, the address of the actual arguments in the calling function are copied into the formal arguments of the called function. This means using the formal arguments ( the address of the original values) in the called function, we can make changes in the actual arguments of the calling function.

Therefore in this method the called function does not create its own copies of the original values rather it refers to the original values by the addresses (passed through pointers) it receives.

Example:1

//to swap two values : By passing  pointers
#include<stdio.h>
#include<conio.h>
void swap(int *p,int *q);
int main()
{
	int a,b;
	printf("Enter 2 numbers ");
	scanf("%d %d",&a,&b);
	swap(&a,&b);
	printf("in main function\n");
	printf("1st value %d 2nd value %d\n",a,b);
	getch();
	return(0);
}
void swap(int *p,int *q)
{
	int t;
	t=*p;//1
	*p=*q;//2
	*q=t;//3
}
/* Output */

Enter 2 numbers 10
20
in main function
1st value 20 2nd value 10

Example:2

//by passing pointers
#include<stdio.h>
#include<conio.h>
void abc(int *n)
{
  *n=100;
}
int main()
{
  int a=10;
  printf("a= %d\n",a);
  abc(&a);
  printf("a= %d\n",a);
  getch();
  return(0);
}
/* Output */

a= 10
a= 100