Re: Min and max of a POD
On Jul 3, 12:23 am, Howard Hinnant <howard.hinn...@gmail.com> wrote:
On Jul 2, 5:24 pm, "Adem24" <ade...@adem24adem24.org.invalid> wrote:
What is the best way to get the minimum value
and the maximum value an integral POD can hold
without using any external definitions like INT_MIN, INT_MAX etc.?
The type (short, int, long, etc.) plus signed/unsigned is known.
Would you be willing to make an assumption such as a two's
complement representation? Without some assumption like that,
I see no way to query the min/max without external
definitions. With such an assumption, the signed-ness can be
queried without external definitions as well.
For the unsigned, the representation of negative numbers is
irrelevant: the minimum is always 0, and the maximum
"~static_cast< Type >( 0 )" (or "static_cast< Type >( 0 ) - 1",
whichever you prefer).
For most systems, the maximum of a signed value can be obtained
by taking the maximum of the corresponding unsigned (as above),
then shifting it right 1 (still as unsigned). The minimum is a
bit tricky, but you should be able to do it by testing the 2
lower bits of -1, to add the special handling for 1's complement
and signed magnitude: I think the following should work:
- maximum - (static_cast< Type >( -1 ) & 3) == 3)
The only problem is on machines where the maximum value of an
unsigned is equal to the maximum value of the corresponding
signed. (The only two possibilities known to me are that the
unsigned uses the sign bit as part of its value, meaning that
shifting its max one to the right gives the max of a signed, or
that it ignores the sign bit, so that the max of the signed is
equal to the max of the unsigned. Regretfully, I don't know of
any way to determine which one holds, other than by using
external information. On the other hand, the only processor I
know where the unsigned simply ignore the sign bit is the Unisys
MCP, which isn't really a consideration for most people.)
In practice, of course, I use the constants defined in <climits>
if I need an integral constant expression, and the class
template numeric_limits (from <limits>) if I need the value for
a template argument. (And I wait until the next release of the
standard if I need both:-).)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34