T
Tim Rentsch
Francois Grieu said:Peter Nilsson wrote : [snip]if ((size_t) -1 <= UINT_MAX)
I have always wondered if these are equivalent. To reduce to a
simpler thing, how do we demonstrate the following holds?
(unsigned long)~(unsigned long)0 == (unsigned long)-1
The expression (size_t) -1 is guaranteed to be the maximum
value that a (size_t) can have, because of the rules for
how out-of-range values are converted to unsigned types.
[snip]
Of course, you could just roll your own %zu printer...
#include <stdio.h>
int fputz(size_t z, FILE *fp)
{
char b[(sizeof(z) * CHAR_BIT + 5)/ 3];
char t, *p, *q;
q = b;
do
{
*q++ = '0' + (z % 10u);
This is portable to every machine I know, but in this group,
*q++ = "0123456789"[z % 10u];
might be even less objectionable.
The expression '0' + z%10 is guaranteed to work (assuming
z is non-negative), because the standard says decimal digits
have increasing-by-one values after '0'.
} while (z /= 10u);
*q = 0;
for (p = b; p < --q; p++)
{
t = *p;
*p = *q;
*q = t;
}
return fputs(b, fp);
}
Francois Grieu
Again the admittedly pedantic (now fixed):
[long function snipped]
Why not just take Peter's suggestion, modified to always use
printf() rather than taking a (FILE *)? His function can be
shortened a bit, but even as is it has a pretty small footprint,
and doesn't need any integer types other than size_t (and char,
which doesn't count).