C++引用和指针简单样例对比

本文通过一个具体的 C++ 程序实例,演示了如何使用宏定义实现两个整数变量的交换,并通过引用传递的方式进行展示。文章对比了指针和引用在函数参数传递中的不同之处。

宏swap  http://blog.youkuaiyun.com/u014646950/article/details/51603374

c中没有引用,c++才有引用

所以此处用的g++编译


//compile:g++ p_quote.c
//run: ./a.out
//c中没有引用,C++中有引用

#include<stdio.h>
#define swap(a,b) ((a)^=(b),(b)^=(a),(a)^=(b))
void pq(int &a,int &b)
{

  printf("quote a=%d b=%d\n",a,b);
  printf("quote &a=%d &b%d\n",&a,&b);
  swap(a,b);//交换

}
void p(int *a,int*b)
{
  printf("point a=%d b=%d\n",a,b);
  printf("point &a=%d &b=%d\n",&a,&b);
  printf("point *a=%d *b=%d\n",*a,*b);
   swap(*a,*b);//交换
}

int main()
{

   int aa=0,bb=1;
   printf("main val %d %d\n",aa,bb);
   printf("main addr %d %d\n",&aa,&bb);
   pq(aa,bb);
   printf("after quote  swap:a=%d b=%d\n",aa,bb);
   p(&aa,&bb);
   printf("after point  swap:a=%d b=%d\n",aa,bb);
  return 0;
}



屏幕输出

main val 0 1
main addr -1451064500 -1451064504
quote a=0 b=1
quote &a=-1451064500 &b-1451064504
after quote  swap:a=1 b=0
point a=-1451064500 b=-1451064504
point &a=-1451064536 &b=-1451064544
point *a=1 *b=0
after point  swap:a=0 b=1


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值