|
|

楼主 |
发表于 2004-2-19 08:32:38
|
显示全部楼层
程序测试好了,好像没有溢出问题:
swapint.c
#include <stdio.h>
int swapint(int a,int b){
//int a = a1;
//int b = b1;
printf("before:\n a=%x\nb=%x\n",a,b);
printf("before in hex\na=%d\nb=%d\n",a,b);
printf("* * * * * * *\n");
a=a+b;
printf("new a=%d\n",a);
b=a-b;
a=a-b;
printf("finally\n a=%d\nb=%d\n",a,b);
printf("finally in hex\n a=%x\nb=%x\n",a,b);
return 0;
}
swapmain.c:
#include "swapint.c"
//16bits operations 2^16
#define A1 65535
#define B1 65534
//32bits operations 2^32
#define A2 2147483647
#define B2 2147483646
#define A3 -2147483647
#define B3 -2147483646
#define A4 -1//to test ffffffff+fffffff
#define B4 -1
int main(){
swapint(A1,B1);
swapint(A2,B2);
swapint(A3,B3);//test 2*(-2147483648)
swapint(A4,B4);
return 0;
}
运行结果:
bash-2.05b$ gcc -g -o swap2 swapmain.c
bash-2.05b$ ./swap2
before:
a=ffff
b=fffe
before in hex
a=65535
b=65534
* * * * * * *
new a=131069
finally
a=65534
b=65535
finally in hex
a=fffe
b=ffff
before:
a=7fffffff
b=7ffffffe
before in hex
a=2147483647
b=2147483646
* * * * * * *
new a=-3 <- 注意这里有溢出
finally
a=2147483646
b=2147483647
finally in hex
a=7ffffffe
b=7fffffff
before:
a=80000001
b=80000002
before in hex
a=-2147483647
b=-2147483646
* * *= * * * *
new a=3 <- 注意这里有溢出
finally
a=-2147483646
b=-2147483647
finally in hex
a=80000002
b=80000001
before:
a=ffffffff
b=ffffffff
before in hex
a=-1
b=-1
* * * * * * *
new a=-2
finally
a=-1
b=-1
finally in hex
a=ffffffff
b=ffffffff
说明一下:
模拟一下寄存器:(这里是16位的,但其实是32位的,但原理是一样的)
1111,1111,1111,1111+
1111,1111,1111,1110=
1111,1111,1111,1101(a+b)<-寄存器中的 a+b
a-b
1111,1111,1111,1101+
0000,0000,0000,0001+
0000,0000,0000,0001=
1111,1111,1111,1111
所以最后结果不会造成溢出(不管是地址,整数或字符)
但做加法时会溢出,但不影响最后结果
但总觉得那个加法会有不妥当的地方。。。
|
|