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;
}

运行结果

猜你喜欢

转载自www.cnblogs.com/hspzm/p/11751549.html