C++函数形参与实参交换

c++中函数的实参传递到形参的值是单向的,改变形参并不会影响实参。

#include <iostream>
using namespace std;
void swap(int a, int b) {
    int t;
    t = a;
    a = b;
    b = t;
}
int main() {
    int x, y;
    cin>> x >>  y;
    cout << "x=" << x << " y=" << y << endl;
    swap(x, y);
    cout << "x=" << x << " y=" << y << endl;
    return 0;
}

运行结果如下

通过交换,并没有改变x,y的值,为了达到交换的目的,需要通过加&,通过地址的交换而改变x,y的值

#include <iostream>
using namespace std;
void swap(int &a, int &b) {
    int t;
    t = a;
    a = b;
    b = t;
}
int main() {
    int x, y;
    cin>> x >>  y;
    cout << "x=" << x << " y=" << y << endl;
    swap(x, y);
    cout << "x=" << x << " y=" << y << endl;
    return 0;
}

运行结果

 

posted @ 2019-10-28 12:36  北冰洋L  阅读(601)  评论(0编辑  收藏  举报