Re: ptrdiff_t maximum
- From: Ben Bacarisse <ben.usenet@xxxxxxxxx>
- Date: Thu, 26 Aug 2010 13:57:09 +0100
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.
.
- Follow-Ups:
- Re: ptrdiff_t maximum
- From: John Kelly
- Re: ptrdiff_t maximum
- References:
- ptrdiff_t maximum
- From: John Kelly
- Re: ptrdiff_t maximum
- From: Ian Collins
- Re: ptrdiff_t maximum
- From: John Kelly
- ptrdiff_t maximum
- Prev by Date: Re: trim whitespace
- Next by Date: Re: trim whitespace v3
- Previous by thread: Re: ptrdiff_t maximum
- Next by thread: Re: ptrdiff_t maximum
- Index(es):
Relevant Pages
|