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

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

问题描述

当比较无符号值时,如下测试:

When comparing a unsigned value, as in this test:

if (pos == (size_t)-1)

这种比较技术上与以下内容不同:

Is this comparison technically different from something like:

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 是无符号类型,无符号类型遵循通常的模算术规则(其中模数是类型的值表示中的位数的两倍,参见3.9 / 4),因此 -1 转换为 size_t 必须是该类型可以表示的最大值。

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 表示中的所有位。该结果的值取决于您的平台上 int 的表示形式。该值(可能是一个陷阱表示,感谢@Matt McNabb)然后转换为 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 以二进制补码表示,则〜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天全站免登陆