当前位置:C++技术网 > 资讯 > 求大神帮忙语言问题小弟实在不明白

求大神帮忙语言问题小弟实在不明白

更新时间:2016-02-10 12:42:28浏览次数:1+次

#include <iostream.h>
void swap(int a,int b);
int main()
{
int x=8,y=10;
int t=0;
cout<<"x="<<x<<"   y="<<y<<endl;
swap(x,y);
cout<<"x="<<x<<"   y="<<y<<endl;
cout<<"t in main is :"<<t<<endl;
return 0;
}
void swap(int a,int b)
{
int t;
t=a;
a=b;
b=t;
cout<<"t in swap is: "<<t<<endl;
}

x=8   y=10                     输出main函数中xy原值
t in swap is: 8                调用swap函数并输出swap中的t的值
x=8   y=10                      输出调用函数后的xy值
t in main is :0                  输出main函数的t的值
Press any key to continue

解答:
swap函数用传值来处理交换,是无法达到效果的。传入的值是一个参数,会产生临时变量。
所以,即使交换,也只是临时变量的交换,和外面的变量无关。外面的变量将值传入swap,修改的却是局部的临时变量,对外部的变量没有任何影响。这是一个误区!
如果需要交换,用指针或者引用来传参,这样函数内部的交换,也就会直接修改了外部的变量的值。