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

交换两个整型量,不用到临时变量,但这种方法在什么情况下不行?该如何解决

2012-03-25 
交换两个整型量,不用到临时变量,但这种方法在什么情况下不行?void swap(int& x1,int& x2){x1x1^x2x2x1^

交换两个整型量,不用到临时变量,但这种方法在什么情况下不行?
void swap(int& x1,int& x2)
{
x1=x1^x2;
x2=x1^x2;
x1=x1^x2;
}
或者为:
void swap(int& x1,int& x2)
{
x2=x1+x2;
x1=x2-x1;
x2=x2-x1;
}
什么时候这种方法不行??

[解决办法]
前者不能swap(a,a);//a会变为0
后者不能x1=2147483647;x2=2147483647;swap(x1,x2);//可能会抛出加法溢出异常。

C/C++ code
#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
[解决办法]
上面的说的情况应该是对的,这里再给上一处希望对楼主有点作用。。http://www.cppblog.com/w57w57w57/

热点排行