What is Call by Value?
Call by value is known as the method for parameter passing. In this method of calling by value, in the formal parameters, the value of the actual parameter is copied. In this, a different memory is allocated for each type of parameter. The advantage of using the call by value method is that the original variable does not change with the change in calling by value.
In this method by using a formal parameter, it is not possible to change or modify the value of the actual parameter. The actual value of the actual argument is not varied either. Let us see an example of a Call by value"
Input:
void main() {
int a = 5,
void decrement(int);
Cout << "before function calling" << a;
increment(a);
Cout << "after function calling" << a;
getch();
void increment(int x) {
int x = x - 1;
Cout << "value is" << x;
}
Output:
before function calling 5
value is 5
after function calling 4
What is Call by Reference?
Call by reference is also a method for parameter passing. In this method address or reference is passed to a function. The call by reference parameter is also known as the pointer variable. The original value of the function changes with a call by reference. In languages such as C++ or Java, call by reference is preferred to call by value.
Let us see the example of call by reference before finally reading about the difference between call by value and call by reference.
Input:
void swap(int *c, int *d){
int temp;
temp=*c;
*c=*d;
*d=temp;
}
void main(){
int c=200, d=400;
swap(&a, &b); // passing value to function
printf("nValue of a: %d",a);
printf("nValue of b: %d",b);
}
Output:
Value of a: 400
Value of b: 200
Difference Between Call by Value and Call by Reference
In languages such as C++ or Java, either of the following call by reference or call by value approaches can be used based on the requirement of the programmer. Let us now see the difference between call by value and call by reference in the following table in order to know where to use which method for better results:
Difference Between Call by Value and Call by Reference | |
Call by Value | Call by Reference |
Values are passed by copying variables. | Values are passed by copying the address of the variables. |
Copies are passed. | Variable is passed. |
Changes do not reflect the original function. | Changes affect the variable of the function. |
The actual variable can not be changed | The actual variable can be modified. |
The argument is also safe from the changes. | The argument also changes with a change in the called function. |
The different memory location is used to create the actual and formal arguments. | The same memory location will be used. |
Used in C++, PHP, C#, etc. | Used in Java, C++, etc. |
Comments
write a comment