5.3重学C++之【指针与函数】

#include<iostream>
using namespace std;




void swap1(int a, int b){
    int temp = a;
    a = b;
    b = temp;
    cout << "swap1 a=" << a << endl;
    cout << "swap1 b=" << b << endl;
}


void swap2(int * p1, int * p2){
    int temp = *p1;
    *p1 = *p2;
    *p2 = temp;
}


int main(){
    /*
        指针与函数
    */

    int a = 10;
    int b = 20;
    cout << "a=" << a << endl;
    cout << "b=" << b << endl;

    // 1 值传递
    swap1(a, b); // 值传递不会改变实参
    cout << "a=" << a << endl;
    cout << "b=" << b << endl;

    // 2 地址传递
    swap2(&a, &b); // 地址传递可以改变实参
    cout << "a=" << a << endl;
    cout << "b=" << b << endl;

    return 0;
}

posted @ 2021-03-09 20:39  yub4by  阅读(17)  评论(0编辑  收藏  举报