Call by value in C

Call by value in C

Call by value in C is a method of passing arguments to a function that duplicates the actual value of an argument into the formal parameter of the function.

The code within a function cannot alter the arguments used to call the function. Changes made to the parameter inside the function have no effect on the argument. when calling a function we are passing values of variables to it.

In this method different memory is allocated for formal and actual parameters so, the value of the actual parameter is copied into the formal parameter and the value of each variable in the calling function is copied into dummy variables of the call function.

 

Program

#include <stdio.h>
int increment(int var)
{
    var = var+1;
    return var;
}

int main()
{
   int no1=20;
   int n02 = increment(num1);
   printf("no1 value is: %d", no1);
   printf("\nno2 value is: %d", no2);

   return 0;
}

Output

no1 value is: 20
no2 value is: 21

 

Explanation

We pass the variable no1 while calling the method, but since we are calling the function using the call by value method

only the value of no1 is copied to the formal parameter var. Thus change made to the var doesn’t reflect in the no1.

 

Advantages of using Call by value method

  • The method does not change the original variable, so it is protecting data.
  • Whenever a function is called it, never affects on actual contents of the actual arguments.
  • Value of actual arguments passes to the formal arguments, so any changes made in the formal argument do not affect the real cases.

 

 

Also, read the Double Pointer in C

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *