1、值传递
#include<bits/stdc++.h>
using namespace std;
void swap(int a,int b){
int temp;
temp=a;
a=b;
b=temp;
}
int main(){
int a,b;
cin>>a>>b;
swap(a,b);
cout<<a<<' '<<b;
}
这里输入2 3
输出还是2 3
并没有发生交换
因为swap函数中的a,b和主函数中的a,b不是同一个变量参数
主函数把自己a,b的值传递给swap的a,b
swap把自己的a,b交换后没有再传递给主函数
2、指针传递
#include<bits/stdc++.h>
using namespace std;
void swap(int *a,int *b){
int temp;
temp=*a;
*a=*b;
*b=temp;
}
int main(){
int a,b;
cin>>a>>b;
swap(&a,&b);
cout<<a<<' '<<b;
}
输入2 3
输出3 2
3、引用传递
#include<bits/stdc++.h>
using namespace std;
void swap(int &a,int &b){
int temp;
temp=a;
a=b;
b=temp;
}
int main(){
int a,b;
cin>>a>>b;
swap(a,b);
cout<<a<<' '<<b;
}
输入2 3
输出3 2
因为swap函数的a,b就是主函数的a,b