函数间的参数传递
值调用:
//交换两个变量的值(不成功)
#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;
}