Call by value and Call by reference in C
There are two methods to pass the data into the function in C language, i.e., call by value and call by reference. call by value and call by reference in c Let’s understand call by value and call by reference in c language one by one.
Call by value
1) In call by value method, the value of the actual parameters is copied into the formal parameters. In other words, we can say that the value of the variable is used in the function call in the call by value method.
2) In call by value method, we can not modify the value of the actual parameter by the formal parameter.
3) In call by value, different memory is allocated for actual and formal parameters since the value of the actual parameter is copied into the formal parameter.
4)The actual parameter is the argument which is used in the function call whereas formal parameter is the argument which is used in the function definition.
flow of Call by value and Call by reference
Code Example
#include<stdio.h>
void change(int num) {
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(x);//passing value in function
printf("After function call x=%d \n", x);
return 0;
}
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100
Call by Value Example: Swapping the values of the two variables
#include<stdio.h>
void swap(int , int); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in main
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual parameters do not change by changing the formal parameters in call by value, a = 10, b = 20
}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a = 20, b = 10
}
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100
What is the use of call by value?
The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. By default, C programming uses call by value to pass arguments.
What is calling function in C?
A function is a group of statements that together perform a task. A function declaration tells the compiler about a function’s name, return type, and parameters. A function definition provides the actual body of the function. The C standard library provides numerous built-in functions that your program can call.