Often values are known to be positive. For example TCP/UDP sequence number is always positive value. Both int and unsigned int are big enough to store even the biggest sequence number so I can use any of these types. There are many other examples when values are known to be positive.
Are there any reasons to use unsigned type when capacity of regular signed type is enough (and often more than enough)?
Personally I tend to use regular types because:
int is probably a little bit more readable than uint or unsigned int
UINT etc.Reasons to use unsigned type I can imagine:
Unsigned integers are used when we know that the value that we are storing will always be non-negative (zero or positive). Note: it is almost always the case that you could use a regular integer variable in place of an unsigned integer.
You should use unsigned values whenever you are dealing with bit values, i.e. direct representations of the contents of memory; or when doing manipulations such as bit masking or shifting on data, for example when writing low-level code to read binary file formats such as audio files; or if you happen to be doing work ...
In summary, signed is a good general choice - even when you're dead sure all the numbers are positive - if you're going to do arithmetic on the variable (like in a typical for loop case). unsigned starts to make more sense when: You're going to do bitwise things like masks, or.
Signed versus unsigned integers In most cases, there is no difference in speed between using signed and unsigned integers. But there are a few cases where it matters: Division by a constant: Unsigned is faster than signed when you divide an integer with a constant. This also applies to the modulo operator %.
One reason is that comparing signed and unsigned numbers can lead to surprising results. In C and (I think) C++, comparing signed and unsigned numbers causes the signed number to be interpreted as unsigned. If the signed value happens to be negative, reading it as unsigned will give a LARGER value than any unsigned number, which is not what you want. See this question for an example in Objective-C, which uses the same conversion rules as C.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With