Friday 21 October 2016

c++ - Diff Between Call By Reference And Call By Pointer





Can any one tell me the exact diff between call by pointer and call by reference. Actually what is happening on both case?



Eg:



Call By Reference:



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;
}

swap(a, b);


Call By Pointer:




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;
}


swap(&a, &b);

Answer



The both cases do exactly the same.



However, the small difference is, that references are never null (and inside function you are sure, that they are referencing valid variable). On the other hand, pointers may be empty or may point to invalid place in memory, causing an AV.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...