# Re: ptrdiff_t maximum

John Kelly <jak@xxxxxxxxxxxx> writes:
<snip>
Here's another try at the elusive universal solution for the maximum
value of any signed type.

<snip>
# define MAX_SIGNED_BITS(type) (sizeof (type) * CHAR_BIT - 1)

# define MAX_SIGNED(type, name) \
\
type \
name ## _max_ (void)\
{ \
type last; \
int tn, bits = MAX_SIGNED_BITS(type); \
for (last = 1, tn = 1; tn < bits; tn++) { \
last = last * 2 + 1; \
} \
return last; \
}

Why the loop? The result is statically determined from the value of
MAX_SIGNED_BITS(type). If the type has padding bits, this method does
not work. If you are happy with a solution that assumes there are no
padding bits, then a version has already been posted that produces
a compile-time constant. No need for a function nor a loop.

MAX_SIGNED (short, short);
MAX_SIGNED (ptrdiff_t, ptrdiff_t);
MAX_SIGNED (long long, long_long);

int
main (void)
{
short const short_max = short_max_ ();
ptrdiff_t const ptrdiff_t_max = ptrdiff_t_max_ ();
long long const long_long_max = long_long_max_ ();

printf ("short_max = %d\n", short_max);
printf ("ptrdiff_t_max = %d\n", ptrdiff_t_max);

This is undefined. In C99 there is the t size modifier and in C90
ptrdiff_t can't be wider than long so casting to long and using %ld is
the standard way to print a ptrdiff_t.

printf ("long_long_max = %lld\n", long_long_max);

return 0;
}

--
Ben.
.

## Relevant Pages

• Re: ptrdiff_t maximum
... value of any signed type. ... I can't find much info on the padding bits you mention. ... you need to change this if you don't have a C99 ...
(comp.lang.c)
• Re: ptrdiff_t maximum
... value of any signed type. ... I can't find much info on the padding bits you mention. ... In C99 there is the t size modifier and in C90 ...
(comp.lang.c)
• Re: Various DOM-related wrappers (Code Worth Recommending Project)
... var start = ).getTime; ... sugar on top of what the browser offers. ... this was in a loop and I thought the join would be faster. ...
(comp.lang.javascript)
• Re: newbie: need inspiration
... Value holding input isn't really ... Loop should end when user ... That would be overloading the variable (it now has 2 purposes - ...
(comp.unix.shell)
• Re: foreach vs for
... > c-style loop and the foreach loop was an iterator. ... Note, this is not real Huffman encoding, just Larry Wall's version of it. ...
(perl.beginners)