搜索
bottom↓
回复: 7

关于整型不会小于0警告 怎么处理?

[复制链接]

出0入0汤圆

发表于 2012-4-29 23:47:14 | 显示全部楼层 |阅读模式
RT

  u8 i;

  for (i=31;i>=0;i--)

一般来讲写 i>=0 比较放心,但如果 这样写就会Warning:

pointless comparison of unsigned integer with zero


阿莫论坛20周年了!感谢大家的支持与爱护!!

一只鸟敢站在脆弱的枝条上歇脚,它依仗的不是枝条不会断,而是自己有翅膀,会飞。

出0入4汤圆

发表于 2012-4-29 23:52:45 | 显示全部楼层
编译器是对的,如果你这样写,程序会一直执行,不会结束的

出0入0汤圆

 楼主| 发表于 2012-4-29 23:55:06 | 显示全部楼层
哈,是 i-- 哦

出0入0汤圆

 楼主| 发表于 2012-4-29 23:57:00 | 显示全部楼层
网上搜到一文:

原地址: http://mtlin.org/archives/3434

拿 unsigned integer 跟 0 做大小比較沒意義嗎?Linus Torvalds 不這麼認為…
Posted on November 24, 2004 by mtlin

有人要動 file system 底下的程式 fcntl.c,原因是要修掉一個 compiler 的 warning: pointless comparison of unsigned integer with zero。但有人說他以前就提出過,卻被 Linus 給回絕。於是這次提出的傢伙就不信邪地再 CC 去問 Linus … XD

但是 Linus Torvalds 卻還是認為有留下檢查的必要,底下是他的回覆:

    No, please don’t.

    The warning is sometimes useful, but when it comes to a construct like

       if (a < 0 || a > X)

    the fact that “a” is unsigned does not make the construct silly. First off, it’s (a) very readable and (b) the type of “a” may not be immediately obvious if it’s a user typedef, for example.

    In fact, the type of “a” might depend on the architecture, or even compiler flags. Think about “char” – which may or may not be signed depending on ABI and things like -funsigned-char.

    In other places, it’s not “unsigned” that is the problem, but the fact that the range of a type is smaller on one architecture than another. So you might have

       inf fn(pid_t a)
       {
          if (a > 0xffff)
          …
       }

    which might warn on an architecture where “pid_t” is just sixteen bits wide. Does that make the code wrong? Hell no.

    IOW, a lot of the gcc warnings are just not valid, and trying to shut gcc

    It’s not even that I will drop the patches, it’s literally that “fixing” the code so that gcc doesn’t complain can be a BUG. We’ve gone through that.

    Linus

原始討論串在此:http://kerneltrap.org/mailarchiv ... 11/21/307540/thread 後頭還有一些其他人的意見,可以參考。

出0入0汤圆

发表于 2012-4-29 23:59:12 | 显示全部楼层
本帖最后由 Goselff 于 2012-4-30 00:01 编辑

这样做,肯定会一直执行,因为是U8类型,所以0-1等于255,还是大于0,程序会死在这里的。
可以这样写:for(i=31;i<=31;i--);这样当从0减到255时,就停止执行了。

出0入0汤圆

 楼主| 发表于 2012-4-30 00:05:33 | 显示全部楼层
Goselff 发表于 2012-4-29 23:59
这样做,肯定会一直执行,因为是U8类型,所以0-1等于255,还是大于0,程序会死在这里的。
可以这样写:for( ...

嗯,有道理。

出0入0汤圆

发表于 2012-4-30 12:08:54 | 显示全部楼层
for(i=31;i<=31;i--); 有道理!

出0入0汤圆

发表于 2012-5-1 10:47:26 | 显示全部楼层
语法糖

linus扯了半天,根本原因就是编译器优化问题

while(1)也是一个道理的。
回帖提示: 反政府言论将被立即封锁ID 在按“提交”前,请自问一下:我这样表达会给举报吗,会给自己惹麻烦吗? 另外:尽量不要使用Mark、顶等没有意义的回复。不得大量使用大字体和彩色字。【本论坛不允许直接上传手机拍摄图片,浪费大家下载带宽和论坛服务器空间,请压缩后(图片小于1兆)才上传。压缩方法可以在微信里面发给自己(不要勾选“原图),然后下载,就能得到压缩后的图片】。另外,手机版只能上传图片,要上传附件需要切换到电脑版(不需要使用电脑,手机上切换到电脑版就行,页面底部)。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

手机版|Archiver|amobbs.com 阿莫电子技术论坛 ( 粤ICP备2022115958号, 版权所有:东莞阿莫电子贸易商行 创办于2004年 (公安交互式论坛备案:44190002001997 ) )

GMT+8, 2024-5-12 07:38

© Since 2004 www.amobbs.com, 原www.ourdev.cn, 原www.ouravr.com

快速回复 返回顶部 返回列表