Re: Stroustrup's TC++PL(se) section 4.4
Wayne Shu wrote:
:: Now I'm reading Stroustrup's The C++ Programming Language(Special
:: Edition).
::
:: In section 4.4 Integer Types, he has wrote that "Using an unsigned
:: instead of an int to gain one more bit to represent positive
:: integers is almost never a good idea. Attempts to ensure that some
:: values are positive by declaring variables unsigned will typically
:: be defeated by the implicit conversion rules".
::
:: I can't understand the two sentences.
::
:: The first: "Using an unsigned instead of an int to gain one more
:: bit to represent positive integers is almost never a good idea."
:: Why? If int is represented as a two's complement method, it's true
:: that we can gain one more bit to represent positive integers using
:: an unsigned.
The real problem is that it genrally won't help. At least not for very
long.
Think about it, if your interface has parameters that don't fit in 31
bits, what are the odds that they will fit in 32 bits? How long will
it take before they sometimes need 33 bits?
:: The second: "Attempts to ensure that some values are positive by
:: declaring variables unsigned will typically be defeated by the
:: implicit conversion rules".
:: In the implicit conversion rules, I think declaring variables
:: signed also has problems, why he explicit mentioned unsigned, but
:: not signed?
You cannot assure that the parameter really is positive, because the
language allows you to assign negative values to an unsigned variable
or parameter.
The REAL problem occurs when you try to mix signed and unsigned types
in the same expression. That is really nasty! One way to avoid that is
to only use signed variables.
Bo Persson