传址函数写法

最近先看看基础的东西。

函数的形参可以传地址或指针,以便在函数里面改值;下面swap的两种写法都可。

代码如下:

#include<cstdio>
using namespace std;
int a,b;
void swap(int* x,int* y)//*可写在空格后 
{
    int t=*x;
    *x=*y;
    *y=t;
}
void swap2(int& x,int& y)//&可写在空格后 
{
    int t=x;
    x=y;
    y=t;
}
int main()
{
    scanf("%d%d",&a,&b);
    swap(&a,&b);
    swap2(a,b);
    printf("a=%d b=%d\n",a,b);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Zinn/p/13394188.html