In article < >,
(Neil Zanella) wrote:
> Hello,
>
> Often I happen to be dealing with nonnegative integers and since I know I
> won't
> need negative numbers here I declare them as unsigned simply to make the
> program
> somewhat clearer. Effectively, though, signed integers would often work too
> since
> unless I am doing some modular arithmetic modulo the word length then I
> almost
> never need to use the high bit since the integers I deal with are usually not
> that large, and I would assume this is true of most programs in general.
>
> So, the question is, when you know an integer is not going to be negative, is
> that
> good enough reason to declare it as unsigned, or does doing so somewhat slow
> down
> the computer (e.g. are signed addition, subtraction, etc... somewhat faster
> and
> why would that be so?)?
For signed integers, the C operators +, -, * produce exactly the same
results as the mathematical operators (as long as the results are not
too large). For unsigned integers, the C operators do some pretty weird
things. A trivial example: For which numbers is
x >= y - 1
true if x and y are both signed, both unsigned, one signed and the other
unsigned? For signed numbers, you are quite safe. Both unsigned, and
there is a strange special case for y = 0. One signed and the other
unsigned, and you have to study the C Standard.
It seems what you have are "positive" numbers. "unsigned" is something
completely different; unsigned numbers can behave in completely
unexpected ways. x - 1 is not one less than x in very common cases.
(And some people will be in for some nasty surprises if they switch to a
compiler where unsigned int and unsigned long have different sizes. )