10

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
  • I don't need to include extra headers for UINT etc.
  • I will avoid extra casts somewhere further in the program

Reasons to use unsigned type I can imagine:

  • help compiler generated better code?
  • help another programmer to understand that variable is unsigned
  • avoid possible bugs (for example when int is assigned to UINT compiler likely will generate compile-time error and we should check that value we assign is not negative)
9
  • Some thoughts about it here: embeddedgurus.com/stack-overflow/2009/08/… Commented Apr 24, 2013 at 9:36
  • 1
    thanks, also I've found that question just now stackoverflow.com/questions/12225521/… Commented Apr 24, 2013 at 9:38
  • 1
    No. There are some arguments against using unsigned - Stroustrup alludes to this in passing in The C++ Programming Language somewhere - Lakos went off and wrote a chapter about it in one of his books: tedious. Example issues: if you have values a and b, abs(a - b) tends to work intuitively for ints but not unsigned; and it's noteworthy that Standard conversions can kick in silently so the kind of checks you might hope to get from using unsigned don't work anyway - negative values become silently huge and vice versa. Commented Apr 24, 2013 at 9:39
  • 1
    Mixing signed and unsigned is an important source of bugs. I would stick to signed in all but specialist situations. Commented Apr 24, 2013 at 9:40
  • 1
    @john: not mixing them means not using STL at all? Commented Apr 24, 2013 at 9:46

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.