Day#85 C' Coding Challenge

Day#85 C' Coding Challenge

What is the difference between Call by Value and Call by Reference?

------------------------------------

  • Call by Value and Call by Reference are two ways to invoke functions in C programming
  • When call by value is used, the argument passed as value and any processing on this argument doesn't impact the actual value of the argument. This meant a local instance of the argument is created
  • Call be value example is as follows
int a = 0,b = 0;
func(a, b);

func(int a,int b)
{
    a = 1;
    b = 2;
}

In the above example, when a,b are passed, a copy of a,b are created and further processing of a,b happens, a,b in func() are local to that function and doesn't impact the a,b used in the calling function.
  • In Call by value, we can say that a copy of the variable is passed
  • The arguments passed from calling function are called actual arguments and arguments in the called function are called formal arguments
  • Call by reference is nothing but which passes a reference of the variable which is nothing but address. When address is passed, the actual value of the variable can be changed unlike the call by value
  • Call by reference can be explained by simple example below
int a = 0;
int *ptr = &a;
func(ptr);

func(int *ptr)
{
    *ptr = 1;
}
  • In the above example ptr is a pointer and points to the address of a. This ptr is passed through function func().  As *ptr points to the value at the address of a, when *ptr is changed, the actual value of a is changed

Post a Comment

0 Comments