您的位置:首页 > 其它

使用传递变量引用的方式完成两个数的交换

2012-11-07 19:34 330 查看
#include <iostream>
using namespace std;

int main()
{
void swap(int &a,int &b);
int a=1,b=2;
cout<<a<<" "<<b<<endl;
swap(a,b);
cout<<a<<" "<<b<<endl;
return 0;
}

void swap(int &a,int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}

运行结果:

1 2

1 2

以上运行结果表明并没有完成两个变量的交换。

使用debug工具时,发现函数调用语句swap(a,b);没有执行。

代码修改后:

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

void swap(int &a,int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}

运行结果:

1 2

2 1

以上运行结果表明完成两个变量的交换。

以上两个程序的唯一区别在于函数声明的位置,一个放在main函数外,一个放在main函数内。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: