按引用传递和按地址传递的区别 [英] Differences between passing by reference and passing by address

查看:55
本文介绍了按引用传递和按地址传递的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int func(int a, int& b){
   if (a < 3){
       return b;
   } else{
       b++;
       return func( a/10, b);
   }
}

我认为这里的 b 是通过指针传递的,这与通过引用传递相同.什么是按地址传递,它与按引用传递有何不同?上面有没有通过地址传递的变量?另外,为什么 func(40, 0) 给我一个错误作为输出?

I think b here is passed by pointer which is the same as passing by reference. What is passing by address, how it differs from passing by reference? Is there any variable in above is passed by address? Also, why func(40, 0) gave me an error as output?

推荐答案

让我试着让你以简单的方式理解.当您在 C++ 程序中声明任何变量时,编译器会在符号表中为该变量创建一个条目,然后在内存中为其提供适当的空间.在引用变量的情况下,符号表中将有一个新条目,该条目具有与引用变量相同的存储空间,以后不会为其分配空间,它只是一个别名,就像您可能被两个名称引用一样(例如姓名,昵称).现在让我们以指针变量为例.不管它是一个指针,但它是一个变量,所以它也会有一个符号表条目,稍后会为它分配空间.

Let me try to make you understand in easy way. When you declared any variable in your c++ program then compiler create an entry in the symbol table for that variable and later an appropriate space in memory provided for it. In case of reference variable there will be a new entry in the symbol table which having the same storage of referenced varible, there will be no space allocated for it later, it is just an alias name like you may be refer by two names (like name, nick name). Now lets take a case of pointer varible. Irrespective of it is a pointer but it is a variable so it will also have a symbol table entry and space will be allocated for it later.

所以从上面的语句你可以很容易地找到地址(指针)和引用变量之间的以下区别1) 不会为引用变量分配额外的内存,但对于指针变量,将有 4 或 8 个字节,具体取决于您要为其编译和运行代码的系统(32 位或 64 位操作系统).2)您以后不能正常引用引用变量,因此您不能更改引用,但在指针变量的情况下,它可以包含不同的指针.

So from above statements you can easily find the below difference between address(pointer) and reference variable 1) There will no extra memory allocated for the reference variable but for pointer variable there will be 4 or 8 bytes depends on the system (32 or 64 bit operating system) for which you are going to compile and run the code. 2) you can't deference the reference variable later on normally so you can't changed the reference but in case of pointer variable it can contain different pointer.

同样适用于引用传递和地址传递.希望它能帮助您更好地理解.

The same is applicable for passing by reference and passing by address. Hope it will help you to understand in better way.

尝试执行下面的代码,你会发现变量和引用变量的地址是一样的

Try execute the below code and you will find that the address of variable and reference variable is same

int main()
{
  int i = 10;
  int& j = i;

  printf(" address of i = %u address of j = %u", &i, &j);
  return 0;
}

这篇关于按引用传递和按地址传递的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆