Advice on Unsigned Types

John Kacur (jkacur@home.com)
Thu, 30 Aug 2001 22:11:53 -0400


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
-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@vger.kernel.org
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/