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);
Only difference is that References are used to refer an existing variable in another name whereas pointers are used to store address of variable. It is safe to use reference because it cannot be NULL.
The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. It means the changes made to the parameter affect the passed argument.
References are usually preferred over pointers whenever you don't need “reseating”. This usually means that references are most useful in a class's public interface. References typically appear on the skin of an object, and pointers on the inside.
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.
Semantically these calls have identical results; under the hood references are implemented with pointers.
The important difference between using references and pointers is with references you have a lot less rope to hang yourself with. References are always pointing to "something", where as pointers can point to anything. For example, it is perfectly possible to do something like this
void swap(int *x, int *y)
{
int temp;
temp = *x; /* save the value at address x */
++x;
*x = *y; /* put y into x */
*y = temp; /* put x into y */
return;
}
And now this code could do anything, crash, run, have monkeys fly out of your noes, anything.
When in doubt, prefer references. They are a higher, safer level of abstraction on pointers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With