What is difference between call by value and call by reference? Which one is better?(explain with example)
Answers
Answer:
call value:n call by value, copies of variables are passed to the function. The function may change that copied value but it does not change the original value. This concept can easily be understood by swapping two numbers program. Refer the below C program written using Code Blocks environment.
call reference:n call by value, copies of variables are passed to the function. The function may change that copied value but it does not change the original value. This concept can easily be understood by swapping two numbers program. Refer the below C program written using Code Blocks environment.
Explanation:
DIFFERENCES →_→
Call by value =>
• if any change is made in the formal parameter then that change will not affect the actual parameters
Call by reference =>
• If any changes made in the formal parameters then it will affect the actual parameters
▃▃▃▃▃▃▃▃▃▃▃▃▃▃▃▃▃▃▃▃▃▃▃▃▃
Obviously the call by value is better than CA by reference
▃▃▃▃▃▃▃▃▃▃▃▃▃▃▃▃▃▃▃▃▃▃▃▃▃
• Call bye reference example is given in the previous answer
• Call by value example ➝
class OBH
{
void change ( int x )
{
x = x + 2 ;
}
public static void main ()
{
OBH obj = new OBH() ;
int a = 10 ;
obj.change(a) ;
System.out.prinltn (a) ;
}
}
=> the output should have been 12 but you to call by fellow it becomes 10 as the call by value mainly focuses on that if any change is made on the formal parameters then it will not affect actual parameters