Diff Between Call By Reference And Call By Pointer

2019-03-11 05:12发布

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

标签: c++
5条回答
贪生不怕死
2楼-- · 2019-03-11 05:28

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.

查看更多
一纸荒年 Trace。
3楼-- · 2019-03-11 05:36

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.

查看更多
一纸荒年 Trace。
4楼-- · 2019-03-11 05:52

Your code is C++ code. In Java there are no pointers. Both examples do the same thing, functionally there is no difference.

查看更多
贪生不怕死
5楼-- · 2019-03-11 05:52

I don't know exactly why this was tagged jave as there are no pointers. However, for the concept you can use both pointers and reference interchangeably if you are working on the value attribute. for example i=4 or *i=4. The advantage of using pointers is that you can manipulate the adress itself. Sometimes you will need to modify the adress (point it to something else ...) this is when pointers are different for reference; pointers allow you to work directly on the adress, reference won't

查看更多
smile是对你的礼貌
6楼-- · 2019-03-11 05:52

In your example, there is no difference.

In C++ reference is implemented using pointers.

Edit: for those who believe reference can't be NULL:

int calc(int &arg)
{
    return arg;
}

int test(int *arg)
{
    return calc(*arg);
}

Guess, what will be the result for test(0)?

查看更多
登录 后发表回答