Call By Value in C


In this method of calling the function values of the original variables is passed to the function.
As you pass the values of original variables it is copied in the formal parameters(dummy variable) of the function. Thus function works with the copy of the original variables. Any changes that are made to the variables inside function do not affect the original variables.
Thus call by value method does not alter the value of the original variable.

Example
#include<stdio.h>
#include<conio.h>
void swap (int a, int b);
void main ()
{
   int a, b;
   clrscr ();
   printf ("Enter Two Numbers:");
   scanf ("%d%d", &a, &b);
   printf ("Before Swap\n");
   printf ("A=%d\nB=%d\n", a, b);
   swap (a, b);
   printf ("Before Swap\n");
   printf ("A=%d\nB=%d\n", a, b);
   getch ();
}
void swap (int a, int b)
{
   int c ;
   c = a ;
   a = b ;
   b = c ;
}
Output
Enter Two Numbers: 2 3
Before Swap
A = 2 B = 3
After Swap
A = 2 B = 3
     

Call By Referance


In this method of calling the function addresses of the original variables is passed to the function using concept of pointer.
As you pass the addresses of original variables, the function works with the original variables. Any changes that are made to the variables inside function also affect the original variables.
Thus call by reference method alters the value of the original variable.

Example
#include<stdio.h>
#include<conio.h>
void swap (int *p, int *q);
void main ()
{
   int a, b;
   clrscr ();
   printf ("Enter Two Numbers:");
   scanf ("%d%d", &a, &b);
   printf ("Before Swap\n");
   printf ("A=%d\nB=%d\n", a, b);
   swap (&a, &b);
   printf ("Before Swap\n");
   printf ("A=%d\nB=%d\n", a, b);
   getch ();
}
void swap (int *p, int *q)
{
   int c;
   c = *p;
   *p = *q;
   *q = c;
}
Output
Enter Two Numbers: 2 3
Before Swap
A = 2 B = 3
After Swap
A = 3 B = 2

Download Projects


Download Programs