欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

函数间的参数传递

程序员文章站 2022-04-18 14:37:16
...

函数间的参数传递


值调用:

//交换两个变量的值(不成功)
#include<iostream>
using namespace std;
void myswap(int x, int y)
{
    int tmp = x;
    x = y;
    y = tmp;
}
int main()
{
    int a = 2, b = 3;
    cout<<"Before exchange : a = "<<a<<", b = "<<b<<endl;
    myswap(a, b);
    cout<<"After exchange  : a = "<<a<<", b = "<<b<<endl;
    return 0;
}

引用调用:

//交换两个变量的值(成功)
#include<iostream>
using namespace std;
void myswap(int &x, int &y)
{
    int tmp = x;
    x = y;
    y = tmp;
}
int main()
{
    int a = 2, b = 3;
    cout<<"Before exchange : a = "<<a<<",b = "<<b<<endl;
    myswap(a, b);
    cout<<"After exchange  : a = "<<a<<",b = "<<b<<endl;
    return 0;
}

地址调用:

//交换两个变量的值(成功)
#include<iostream>
using namespace std;
void myswap(int *x, int *y)
{
    int temp = *x;
    *x = *y;
    *y = temp;
}
int main()
{
    int a = 2, b = 3;
    cout<<"Before exchange : a = "<<a<<",b = "<<b<<endl;
    myswap(&a, &b);
    cout<<"After exchange  : a = "<<a<<",b = "<<b<<endl;
    return 0;
}