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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…