Oleg Vazhnev
Oleg Vazhnev

Reputation: 24067

Should I use "unsigned" every time i know I'm processing unsigned values?

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:

Reasons to use unsigned type I can imagine:

Upvotes: 10

Views: 374

Answers (1)

Caleb
Caleb

Reputation: 124997

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.

Upvotes: 1

Related Questions