签名与对长度/计数无符号整数 [英] Signed vs. unsigned integers for lengths/counts

查看:116
本文介绍了签名与对长度/计数无符号整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关重新presenting的长度或计数变量,是它更好地使用签署无符号的整数?

For representing a length or count variable, is it better to use signed or unsigned integers?

在我看来,那C ++ STL趋于preFER的符号的(的std ::为size_t ,像<一个href=\"http://msdn.microsoft.com/en-us/library/3y41k4hb%28v=vs.80%29.aspx%29\">std::vector::size(),而不是C# BCL 趋于preFER的签署的整数(如在的ICollection.Count

It seems to me that C++ STL tends to prefer unsigned (std::size_t, like in std::vector::size(), instead C# BCL tends to prefer signed integers (like in ICollection.Count.

考虑到的长度或计数都是非负整数,我的直觉会选择的符号的;但我不明白为什么.NET设计师选择符号整数。

Considering that a length or a count are non-negative integers, my intuition would choose unsigned; but I fail to understand why the .NET designers chose signed integers.

什么是最好的方法呢?什么是每个人的优点和缺点是什么?

What is the best approach? What are the pros and cons of each one?

推荐答案

C ++使用无符号值。在32位的系统中,语言应该使人们有可能有一个4 GB的载体,而不仅是2 GB的之一。 (操作系统可能不允许你使用所有4 GB,但语言本身并不想在你的方式获得)

C++ uses unsigned values because they need the full range. On a 32-bit system, the language should make it possible to have a 4 GB vector, not just a 2 GB one. (the OS might not allow you to use all 4 GB, but the language itself doesn't want to get in your way)

在.NET中,无符号整数不符合CLS。您可以用它们(在某些.NET语言),但它限制了便携性和兼容性。因此,对于基类库,他们只用符号整数。

In .NET, unsigned integers aren't CLS-compliant. You can use them (in some .NET languages), but it limits portability and compatibility. So for the base class library, they only use signed integers.

不过,这些都是边缘情况。在大多数情况下,签署的 INT 足够大的。
所以,只要双方提供你所需要的范围内,您可以同时使用。

However, these are both edge cases. For most purposes, a signed int is big enough. So as long as both offer the range you need, you can use both.

的一个优点是有符号整数有时是,它们更容易以检测下溢。假设你正在计算数组索引,并且由于一些坏的输入,或者在你的程序也许是逻辑错误,你最终试图访问指数 1

One advantage that signed integers sometimes have is that they make it easier to detect underflow. Suppose you're computing an array index, and because of some bad input, or perhaps a logic error in your program, you end up trying to access index -1.

通过一个有符号整数,这是容易察觉。无符号,它会环绕,成为 UINT_MAX 。这使得它更难被发现的错误,因为你预期的正数,而你的获得的正数。

With a signed integer, that is easy to detect. With unsigned, it would wrap around and become UINT_MAX. That makes it much harder to detect the error, because you expected a positive number, and you got a positive number.

所以真的,它取决于。 C ++使用无符号,因为它需要的范围内。 .NET使用签名的,因为它需要与不语文工作的有无的无符号。

So really, it depends. C++ uses unsigned because it needs the range. .NET uses signed because it needs to work with languages which don't have unsigned.

在大多数情况下,既会工作,有时,可能会签署使您的code,以更有力地检测错误。

In most cases, both will work, and sometimes, signed may enable your code to detect errors more robustly.

这篇关于签名与对长度/计数无符号整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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