Skip to contentSkip to conversation

Advice on Unsigned Types

DISCUSSION John Kacur 2 participants 2 messages Aug 31, 2001 – Sep 5, 2001

lore
Share & tools
lore

John Kacur

author
#0 lore raw

Well, the min/max discussion has been educational if nothing else. There is very good book called "Expert C Programming - Deep C Secrets", by Peter Van Der Linden. (with a picture of a fish on the cover.) He discusses the changes from K&R to ANSI C and quotes from the ANSI C manual on Characters and Integers (the integral promotions) and on Usual Arithmetic Conversions. An example he uses to show a subtle bug that might occur if one doesn't think about these issues, is when using sizeof, which could be hidden away in a macro. sizeof returns an unsigned value. If you compare a negative int to the result of a sizeof operation, it could be converted to an unsigned int and yield a large positive number.

The advice the author give on Unsigned Types is:
"Avoid unnecessary complexity by minimizing your use of unsigned types. Specifically, don't use an unsigned type to represent a quantity just because it will never be negative (e.g."age" or "national debt"). Use a signed type like int and you won't have to worry about boundary cases in the detailed rules for promoting mixed types.
Only use unsigned types for bitfields or binary masks. Use casts in expressions, to make all the operands signed or unsigned, so the compiler does not have to choose the result type."

John Kacur

#1 lore raw
Followup to:  <[email protected]>
By author:    John Kacur <[email protected]>
In newsgroup: linux.dev.kernel
Quoted 11 lines

The advice the author give on Unsigned Types is:
"Avoid unnecessary complexity by minimizing your use of unsigned types. Specifically, don't use an unsigned type to represent a quantity just because it will never be negative (e.g."age" or "national debt"). Use a signed type like int and you won't have to worry about boundary cases in the detailed rules for promoting mixed types.
Only use unsigned types for bitfields or binary masks. Use casts in expressions, to make all the operands signed or unsigned, so the compiler does not have to choose the result type."

So the author isn't talking about developing operating systems. In operating systems it's almost the other way around -- signed is really the exception.

-hpa

Signature · 3 lines
<[email protected]> at work, <[email protected]> in private!
"Unix gives you enough rope to shoot yourself in the foot."
http://www.zytor.com/~hpa/puzzle.txt	<[email protected]>