Types of function calls in C


A function in C programming language can be called by using its name. If the function has no parameters then it can be called by using its name directly. A function that has arguments or parameters can be called by using two different ways:

  1. Call by value
  2. Call by reference


Call by Value:

A function which is called by value is passed with values of arguments. The values of the arguments are stored into the formal parameters of function. Consider the following example in which we have called the function by using values of the arguments:

CODE:

# include <stdio. h>

# include <conio. h>

void inc (int x);

int main ()

{

 int x = 5;

 inc (x);

 printf (“%d”, x);

}

void inc (int x)

{

 x = x + 5;

}

OUTPUT:

5

In the above example the value of the argument that is x is passed to the function and is stored in the formal parameter of the function. In the definition of the function the value of x is incremented by 5 and the control is returned back to the main () function after executing the body of this function. The value of x is printed and it can be seen that it is not changed this is because the function inc () has its own variable x that had a local scope and was known to itself only. When the control is transferred back to the main function the variable of inc () function goes out of scope. And when we printed the variable x inside the main function we got 5.

The value of x can be changed by specifying the return type of the function. If the function returns a value to the main method we can print that changed value:

Consider the following example in which the function is returning a value which is stored in the variable x and is printed:

CODE:

# include <stdio. h>

# include <conio. h>

int inc (int x);

int main ()

{

 int x = 5;

 x = inc (x);

 printf (“%d”, x);

}

int inc (int x)

{

 x = x + 5;

 return x;

}

OUTPUT:

10


Call by reference:

The calling of functions by reference is done using formal parameters. Formal parameters are used in function header. They are used to receive values that are passed to the function in function call. To pass variables as references in a function just reference is used instead of the variable itself.

The following example demonstrates this concept:

# include <stdio. h>

# include <conio. h>

void main ()

{

int a;

a = 1;

addition (a);

printf (“%d”, a);

}

void addition (int& x)

{

x=x+1;

}

OUTPUT:

2


Working of the above program:

In the above example x is a reference of the variable ‘a’. The value of variable ‘a’ is initialized at 1. Then the function is called, the parameter of this function is a reference. The value of this reference is incremented by 1 and now the value of the variable ‘a’ is 2. The control then returns to main () function and the value of ‘a’ is printed.