Types of Function call in C

A function with arguments can be called in two different ways.

  • Call by Value
  • Call by Reference

Call by Value

Calling a function by value means, we pass the values of the arguments which are stored or copied into the formal parameters of the function. Hence, the original values are unchanged only the parameters inside the function changes.

Example

#include<stdio.h>

void calculate(int a);

int main()
{
    int a = 15;
    calculate(a);
    // this will print the value of 'a'
    printf("\nvalue of a in main is %d", a);
    return 0;
}

void calculate(int a)
{
    // changing the value of 'a'
    a = a + 10 ;
    printf("value of a in calc function is %d ", a);
}

Output

value of a in calc function is 25
value of a in main is 15

In the above program, the actual variable a is not changed. Its because we are passing the argument by value, hence a copy of a is passed to the function, which is updated during function execution, and that copied value in the function which gets destroyed when the function ends(goes out of scope). So the variable a inside the main() function is never changed and hence, still holds a value of 15.

Call by Reference

In call by reference, we will be passing the address(reference) of the variable as argument to the function. When we pass the address of any variable as argument, then the function will have access to our variable, as it now knows where it is stored and hence can easily update its value.

In this case the formal parameter can be taken as a reference or a pointers (don't worry about pointers, we will soon learn about them), in both the cases they will change the values of the original variable.

Example

#include<stdio.h>

void calculate(int *p);      // functin taking pointer as argument

int main()
{
    int x = 20;
	// passing address of 'x' as argument
    calculate(&x);       
    printf("value of x is %d", x);
    return(0);
}
//receiving the address in a reference pointer variable
void calculate(int *p)       
{
    /*
        changing the value directly that is 
        stored at the address passed
    */
    *p = *p + 10; 
}

Output

Value of x is 30

Most Read