Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Diff Between Call By Reference And Call By Pointer [duplicate]

Tags:

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);
like image 895
Vinoth Babu Avatar asked Jul 02 '13 10:07

Vinoth Babu


People also ask

What is the difference between call by pointer and call by reference?

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.

What is call by reference in pointer?

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.

Which is better pointer or reference?

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.


2 Answers

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.

like image 119
Spook Avatar answered Oct 23 '22 22:10

Spook


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.

like image 41
Daniel Gratzer Avatar answered Oct 23 '22 23:10

Daniel Gratzer