有没有-1〜0之间的区别吗? [英] Is there a difference between -1 and ~0?

查看:88
本文介绍了有没有-1〜0之间的区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当进行比较的无符号的值,如在此测试

When comparing a unsigned value, as in this test:

if (pos == (size_t)-1)

这是比较技术上从像不同的:

if (pos == (size_t)~0)

我不习惯到第二个变体。这就是为什么我问的问题。答案可能相当简单明了,如果是肯定的。

I am not used to the second variant. That's why I am asking the question. The answer may be rather straighforward if it's yes.

推荐答案

C ++标准保证了为size_t 是一个无符号类型,即无符号类型服从通常的模运算规则(其中,弹性模量为两位的类型的转口货值为presentation数,参见3.9 / 4),因此 1 转换为为size_t 必须是该类型可以重新present的最大值。

The C++ standard guarantees that size_t is an unsigned type, that unsigned types obey the usual modular arithmetic rules (where the modulus is two to the number of bits in the value representation of the type, cf. 3.9/4), and thus -1 converted to size_t must be the largest value which that type can represent.

0 INT 〜0 拥有所有在 INT 重新零翻转presentation位。这一结果的价值取决于 INT 的平台上再presentation。然后该值(其可以是一个陷阱重新presentation,得益于@马特麦克纳布)转化为为size_t (这是继模运算规则完成)。

The value 0 is an int, and ~0 has all the bits in the int representation of zero flipped. The value of that result depends on the representation of int on your platform. That value (which may be a trap representation, thanks @Matt McNabb) is then converted to size_t (which is done following the rules of modular arithmetic).

在最后,将得到的值是否比较相等是实现定义。 (例如,如果 INT 重新在补psented $ P $,则值〜0 1 ,所以两者是相同的。)

In conclusion, whether the resulting values compare equal is implementation defined. (For example, if int is represented in two's complement, then the value of ~0 is -1, so the two are the same.)

这篇关于有没有-1〜0之间的区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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