Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

c# - Signed vs. unsigned integers for lengths/counts

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

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

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.

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.

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.

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.

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...