为什么C编译器无法以直观的方式进行带符号/无符号比较 [英] Why C compiler cannot do signed/unsigned comparisons in an intuitive way

查看:72
本文介绍了为什么C编译器无法以直观的方式进行带符号/无符号比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的意思是直觉"

int a = -1;
unsigned int b = 3;

表达式(a< b)的计算结果应为1.

expression (a < b) should evaluate to 1.

关于Stackoverflow的很多问题已经问到为什么在这种情况下C编译器会抱怨有符号/无符号比较.答案归结为整数转换规则等等.但是,在比较单数和无符号整数时,为什么编译器必须如此异常愚蠢,因此似乎没有理性.使用上面的声明,为什么要这样表达

There is a number of questions on Stackoverflow already asking why in this or that particular case C compiler complains about signed/unsigned comparison. The answers boil down to integer conversion rules and such. Yet there does not seem to be a rationale behind why compiler has to be so exceptionally dumb when comparing singed and unsigned integers. Using declarations above, why expression like

(a < b)

不会自动替换为

(a < 0 || (unsigned int)a < b)

如果没有任何机器指令正确执行此操作?

if there is no single machine instruction to do it properly?

现在,对于以前的问题,有一些评论是如果必须混合有符号和无符号整数,则程序有问题".我不会购买,因为libc本身使它不可能生活在仅签名或未签名的世界中(例如,示例 sprintf()函数族返回 int 作为写入的字节数, send()返回 ssize_t 等).

Now, there have been some comments for previous questions in the vein of "if you have to mix signed and unsigned integers, there is something wrong with your program". I would not buy that since libc itself makes it impossible to live in a signed-only or unsigned-only world (e.g. example sprintf() family of functions returns int as the number of bytes written, send() returns ssize_t and so on).

我也不认为我可以购买下面的评论中表达的想法,即比较中将有符号整数隐式转换为无符号((d-'0'< 10U)"idiom")相对于显式强制转换(((unsigned int)(d-'0')< 10U)).但可以肯定的是,它为搞砸提供了广泛的机会.

I also don't think I can buy an idea expressed in comments below that implicit conversion of signed integer to unsigned in comparison (the (d - '0' < 10U) "idiom") bestows some additional powers on C programmer compared to explicit cast (((unsigned int)(d - '0') < 10U)). But sure enough it opens wide opportunities to screw up.

是的,我很高兴编译器警告我它不能执行该操作(不幸的是,仅当我明确要求它时).问题是-为什么不能呢?通常,标准规则背后有很好的理由,所以我想知道这里是否有任何规则?

And yes, I'm happy that compiler warns me that it cannot do it (unfortunately only if I ask it explicitly). The question is - why can't it? Usually there are good reasons behind standard's rules, so I'm wondering if there are any here?

推荐答案

由于与C语义不同,因此无法进行自动替换,这将严重破坏正确使用该转换的程序.例如:

The automatic replacement cannot be made because that's different from C semantics, and would horribly break programs that use the conversion correctly. For example:

if (d-'0'<10U)  // false if d is not a digit

对于ASCII空间和其他建议替换的字符,将变为true.

would become true for ASCII space and many other characters with your proposed replacement.

顺便说一句,我相信这个问题在一定程度上是重复的:

By the way, I believe this question is partly a duplicate of:

如果我们将安全的有符号/无符号比较添加到C/C ++,会破坏语言或现有代码吗?

这篇关于为什么C编译器无法以直观的方式进行带符号/无符号比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆