Call By Value Vs Call By Reference Vs Call By Address (Pointer) in C++

Icall by value method of passing arguments to function, we pass copies of the actual value as a parameter of the function. In this case, changes made to the parameter inside the called function have no effect on the argument.  Apart from that at backend compiler  create the dummy copies of passed arguments, also compiler  need to create copies for return  values as well. As compiler require multiple copies, time require to execute function is more.  Also function returning multiple values is not straightforward in this method.
void swap(int x, int y) {
int temp; temp = x; // save the value of x x = y; // put y into x y = temp; // put x into y return; }
In the call by reference method, instead of passing copies of actual values,  references of values are passed. Inside the function, the references are is used to access the  values of actual arguments. In short changes made to the parameters affect the original values of  passed arguments.

void swap(int &x, int &y) {
   int temp;
   temp = x; //  save the value at address x 
   x = y;    //  put y into x 
   y = temp; //  put x into y 
  
   return;
}

In call by pointer method of passing arguments to a function copies the address of an argument into the formal parameter. In short we pass pointer i.e variable holding the address of actual value. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument.
void swap(int *x, int *y) {
   int temp;
   temp = *x; //save the value at address x 
   *x = *y;   // put y into x 
   *y = temp; // put x into y 
  
   return;
}
References provide the power of pointers with simpler syntax. The difference between reference and pointer is that pointers are variables holding the address of an object, whereas references are aliases to an object. Reference can not be NULL and  they can not be reinitialised. Generally, C++ programmers strongly prefer references to pointers because they are cleaner and easier to use. Pointers gives more flexibility but are slightly more difficult to use. But if you want to allocate dynamic memory from the heap, you have to use pointers.

That's all for  this post now !!
Bye  

No comments:

Post a Comment

Rendering 3D maps on the web using opesource javascript library Cesium

This is a simple 3D viewer using the Cesium javascript library. The example code can be found here . Click on question-mark symbol on upp...