C Programming language

adplus-dvertising
Calling Function in C
Previous Home Next
  • Call by value
  • Call by reference

Call by value

Whenever we called a function and passed something to it we have always passed the 'Values' of variables to the called function. Such function is called Call By Value.

Example

#include <stdio.h>
#include <conio.h>
main()
{
int
a=50, b=70;
interchange (a, b);
printf (“
a=%d b=%d”, a, b);
}

interchange(a1,b1)
int
a1,b1;
{
int
t;
t=a1;
a1=b1;
b1=t;
printf(“
a1=%d b1=%d”,a1,b1);
}

Output :

a=50 b=70

a1=70 b1=50

Call by reference

We know that variables are stored somewhere in memory. So instead of passing the value of a variable to a function, can we not pass the location number ? If we are able to do so, then it is called 'Call By Reference'.

Example

#include <stdio.h>

void swap (int &a, int &b) // a and b are reference variables
{
int t=a;
a=b;
b=t;
}
This is also accomplished using pointers.
For Example :
void swap1(int t *a, int  *b) 
{
int  t;
t= *a;
*a=*b;
*b=t;
}

swap1(&x, &y);// This function can be called as following  

Example

#include <stdio.h>
#include <conio.h>
main()
{

int num1=
20, num2=3
0;
interchange(&num1,&num2);
printf("num1=%d num2=%d",num1,num2);
}
interchange(num3,num4)
int *num3,*num4;
{
int t;
t=*num3;
*num3=*num4;
*y1num4=t;
printf("*num1=%d *num2=%d",num3,num4);
};

Output:

*num1=70 *num2=50

num1=70 num2=50

In case of call by reference address of the variable got passed and therefore what ever changes that happened in function interchange got reflected in the address location and therefore the got reflected in original function call in main also without explicit return value.

#include <stdio.h>
#include <conio.h>
int factorial (int);
void main
{
int a, fact;
clrscr();

printf("\n Enter any number");
scanf ("%d",&a);
fact=fatorial(a);
printf("factorial value=%d",fact);
}
int factorial(int x)
{
int f=1,i;
for(i=x; i>=1; i--)
f=f*i;
return(f);
};
Previous Home Next