Wednesday, 31 May 2017

Types of Function calls in C ~ GNIITHELP

Types of Function calls in C

Functions are called by their names. If the function is without argument, it can be called directly using its name. But for functions with arguments, we have two ways to call them,
  1. Call by Value
  2. Call by Reference

Call by Value

In this calling technique we pass the values of arguments which are stored or copied into the formal parameters of functions. Hence, the original values are unchanged only the parameters inside function changes.
void calc(int x);
int main()
{
 int x = 10;
 calc(x);
 printf("%d", x);
}

void calc(int x)
{
 x = x + 10 ;
}
Output : 10
In this case the actual variable x is not changed, because we pass argument by value, hence a copy of x is passed, which is changed, and that copied value is destroyed as the function ends(goes out of scope). So the variable x inside main() still has a value 10.
But we can change this program to modify the original x, by making the function calc() return a value, and storing that value in x.
int calc(int x);
int main()
{
 int x = 10;
 x = calc(x);
 printf("%d", x);
}

int calc(int x)
{
 x = x + 10 ;
 return x;
}
Output : 20

Call by Reference

In this we pass the address of the variable as arguments. In this case the formal parameter can be taken as a reference or a pointer, in both the case they will change the values of the original variable.
void calc(int *p);
int main()
{
 int x = 10;
 calc(&x);     // passing address of x as argument
 printf("%d", x);
}

void calc(int *p)
{
 *p = *p + 10;
}
Output : 20
NOTE : If you do not have a prior knowledge of pointers, do study Pointers first.

No comments:

Post a Comment