Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3921892
  • 博文数量: 534
  • 博客积分: 10470
  • 博客等级: 上将
  • 技术积分: 4800
  • 用 户 组: 普通用户
  • 注册时间: 2006-05-26 14:08
文章分类

全部博文(534)

文章存档

2024年(1)

2021年(1)

2019年(1)

2017年(1)

2016年(2)

2013年(2)

2012年(10)

2011年(43)

2010年(10)

2009年(17)

2008年(121)

2007年(252)

2006年(73)

分类: C/C++

2008-03-06 16:55:20

看《深入理解计算机系统》看到,自己也实践了一下:

    当执行一个运算时,如果它的一个运算是有符号的而另外一个是无符号的,那么C会隐含地将有符号参数强制类型转换为无符号数,并假设这两个数都是非负的,来执行这个运算。

如:
---------------------------------
表达式          类型        值
---------------------------------
0 == 0U         无符号      1
1 > 0           有符号      1
-1 > 0U         无符号      1*

2147483647 > -2147483647        有符号   1
2147483647U > -2147483647-1     无符号   0*
2147483647 > (int)2147483648U   有符号   1*

-1 > -2             有符号      1
(unsigned)-1 > -2   无符号      1

[gan@localhost gan]$ gdb
GNU gdb Red Hat Linux (5.3post-0.20021129.18rh)
Copyright 2003 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "i386-redhat-linux-gnu".
(gdb) p -1 > 0U
$6 = 1
(gdb) p -1 < 0U
$8 = 0

(gdb) p 0x7fffffffu > -0x7fffffff-1
$9 = 0
(gdb) p 0x7fffffff
$10 = 2147483647
(gdb) p 2147483647 > -2147483648
$11 = 0
(gdb) p 2147483647 > -2147483647
$12 = 1
(gdb) p -2147483647-1
$13 = -2147483648
(gdb) p -2147483648  
$14 = 2147483648
(gdb) p -10
$15 = -10

上面红色部分是比较需要注意的哦。

   就象我们看到的那样,有符号数到无符号数的隐性强制类型转换导致了某些与直觉不相符的行为。而这些与直觉不相符的特性经常导致程序错误,并且包含隐式强制类型转换的细微差别的错误很难被发现。因为这种强制类型转换是看不到的,我们经常忽视了它的影响。
阅读(3603) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~