LuB wrote:
> This isn't a C++ question per se ... but rather, I'm posting this bcs I
> want the answer from a C++ language perspective. Hope that makes sense.
>
> I was reading Peter van der Linden's "Expert C Programming: Deep C
> Secrets" and came across the following statement:
>
> "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")."
>
<snip>
> -Luther
Well, it is a style issue, so many people will probably disagree with
me. They are probably all right, and I would still be able to respect
them
That said, I personally use signed types almost all the time, even if
something should never be negative. Every once in a while, I make a
horribly stupid error in something like a file loading function.
Suppose an object can have zero or more child objects. If my loader
returns an object that claims to have -1024 children, then I know I've
done something wrong, and it can be easier to track down bugs that
compile and don't crash. If it just claims that there are a large
positive number of children, it's not as easy to catch the error
condition. There is even the wildly unlikely possibility that there is
an error due to a hardware fault like bad RAM. (Though, the problems
are almost always caused by me! Many people who are better programmers
than me may find that hardware accounts for a greater percentage of
problems than I do
Also, I use negative values as intentional error codes and special
cases. Some people consider this horrible style. I can respect that.
But, for a lot of the things I do, it is the quickest, easiest,
simplest, and clearest way to have a recoverable error. So, my
hypothetical object loading function might return an object which
claims -1 children if it failed to open the file, -2 if it failed to
parse the file, -3 if the file contained invalid information, etc. I
know, exceptions are probably better for most of these things, but my
personal style is to write C++ that looks a lot like C, and uses
occasional C++ features. It's just more inline with the way I think
about the problems.
Also, by always using signed types, I can avoid comparisons between
signed and unsigned. It is also generally easier to catch overflow.
After all, the national debt might never be negative, but it certainly
might exceed MAX_INT on some systems!
I tend to work alone on personal projects. So, the most important
thing for me is that my personal coding style is readable - to me.
Feel free to strongly disagree with my style.