首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

实现数值交换,是函数调用呀,为什么不能换呢

2013-10-11 
实现数值互换,是函数调用呀,为什么不能换呢?# include iostreamusing namespace stdvoid swap(int a,in

实现数值互换,是函数调用呀,为什么不能换呢?
# include <iostream>
using namespace std;
void swap(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
int mian()
{
int i=3,j=5;
swap(i,j);
cout<<i<<","<<j<<endl;
return 0;
}
[解决办法]
你的两个例子不一样的!
都是值传递!都是拷贝一份值给函数接口的!
但是一个是传参数,然后最后取参数,一个是传参数,最后取返回值!
楼主找本基础的c语言书看看函数返回值和参数的知识点吧

[解决办法]
如果楼主知道程序的运行时结构,结果一目了然。
对于数值互换程序:
    程序进入main函数后,遇到的i与j是局部非静态成员变量,所以会在栈(进程的运行数据栈)中压入这两个值(姑且称之“第一对数据”),之后调用swap函数。在实参传形参之前先要提高栈顶指针,“压入”参数所需要的两个int型空间,之后在实参传形参时将3与5这两个数据(“第二对数据”)传入空间,之后进行数据交换。
    也就是说发生互换的是第二对数据,第一对数据并没有发生互换而我们输出的恰恰是第一对数据,所以不会发生互换。
    如果楼主对反汇编有所了解,单步执行一下汇编代码一目了然。

[解决办法]

/*
*指针版交换
*/
#include <iostream>
using namespace std;
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
int main()
{
int i=3,j=5;
cout<<"before swap:"<<"i="<<i<<",j="<<j<<endl;
swap(&i,&j);
cout<<"after swap:"<<"i="<<i<<",j="<<j<<endl;
return 0;
}

/*
*引用版交换
*/
#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}
int main()
{
int i=3,j=5;
cout<<"before swap:"<<"i="<<i<<",j="<<j<<endl;
swap(i,j);
cout<<"after swap:"<<"i="<<i<<",j="<<j<<endl;
return 0;
}

[解决办法]
swap函数参数应该使用指针或者引用,否则是按值传递的
[解决办法]
#include <stdio.h>
#define SWAP(a,b) do ((&(a))!=(&(b)))?((a)^=(b)^=(a)^=(b)):((a)=(a)); while (0)
char   *p1="1" ,*p2="2" ;
char    c1=1   , c2=2   ;
short   s1=1   , s2=2   ;
int     i1=1   , i2=2   ;
__int64 I1=1i64, I2=2i64;
float   f1=1.0f, f2=2.0f;
double  d1=1.0 , d2=2.0 ;
void main() {
    SWAP((int)p1,(int)p2);                printf("char *     %5s,   %5s\n",p1,p2);
    SWAP(c1,c2);                          printf("char       %5d,   %5d\n",c1,c2);
    SWAP(s1,s2);                          printf("short      %5d,   %5d\n",s1,s2);
    SWAP(i1,i2);                          printf("int        %5d,   %5d\n",i1,i2);
    SWAP(I1,I2);                          printf("__int64 %5I64d,%5I64d\n",I1,I2);
    SWAP(*(int     *)&f1,*(int     *)&f2);printf("float      %5g,   %5g\n",f1,f2);
    SWAP(*(__int64 *)&d1,*(__int64 *)&d2);printf("double    %5lg,  %5lg\n",d1,d2);

    SWAP(c1,c1);
    printf("%d\n",c1);
}
//char *         2,       1
//char           2,       1
//short          2,       1
//int            2,       1
//__int64     2,    1
//float          2,       1
//double        2,      1


//2

热点排行
Bad Request.