c语言在c99标准中加入了引用
引用的值是地址,指针的值也是地址。
但在编译时,会赋给 引用和指针 不同的意义。
int a = 1;
int *b = &a;
int &c = a;
引用与指针:符号在内存中存的都是地址,都占用字节
编译时有不同的理解:
b:*b表示变量a, b表示a地址,&b表示b的地址
c:*c === *a //把a的值理解为地址,去取值 error
c === a
&c === c
引用能和原变量一样用是因为编译器在编译时做了优化(很重要)
以下网上代码但是我运行的结果不对。
#include<stdio.h>
#include <iostream>
using namespace std;
int main()
{
int x = 1;
int y = 2;
int &b = x;
printf("&x=%x,&y=%x,&b=%x,b=%x\n",&x,&y,&y-1,*(&y-1));
return 0; //
}
// 预料的结果 &x=12ff7c,&y=12ff78,&b=12ff74,b=12ff7c
// 实际 &x=12ff7c,&y=12ff78,&b=12ff74,b=0
自己写的一份:(可以证明引用保存的是地址)
include <bitset>
using namespace std;
int main()
{
int x = 6;
int y = 2;
int *a = &x; //2
int &b = x; //6
int *c = &x; //2
int *d = &x;
printf("&x=%x,&y=%x,&a=%x,c=%x,d=%x\n",&x,&y,&a,&c,&d); //&x=61fe44,&y=61fe40,&a=61fe38,c=61fe30,d=61fe28
// b在 61fe38 61fe30 之间
// 看b的位置 保存的有没有 x的地址 61fe44
printf("%x\n",*(int *)(0x61fe32)); //61
printf("%x\n",*(int *)(0x61fe34)); //0
printf("%x\n",*(int *)(0x61fe36)); //fe440000
//cout << bitset<16>(a) <<endl; //error
//cout << bitset<8>() <<endl;
return 0;
}
截图为证:
我的编译器版本:
引用做入参是不要额外消耗内存原因:
函数参数为引用时,函数的栈不需要额外存储引用,实际上什么也不传,而是直接就用ebp和偏移去找。估计要靠编译器优化和记忆。
sizeof是操作符,并不是函数。这个操作肯定是提前约定好了。
参考:https://blog.csdn.net/huqinwei987/article/details/50769096
https://blog.csdn.net/superwangxinrui/article/details/80565594